Model.findOneAndUpdate ()
调用findOneAndUpdate 即可
let query = { id: id };
let update = { name: 1 };
let options = { upsert: true, new: true, setDefaultsOnInsert: true };
let data = await Model.findOneAndUpdate(query, update, options);
选项
new
:bool-如果为true,则返回修改后的文档,而不是原始文档。默认为false(在4.0中更改)upsert
:bool-创建对象(如果不存在)。默认为false。fields
:{Object | String}-字段选择。相当于.select(fields).findOneAndUpdate()
maxTimeMS
:对查询设置时间限制-需要mongodb> = 2.6.0sort
:如果根据条件找到了多个文档,请设置排序顺序以选择要更新的文档runValidators
:如果为true,则在此命令上运行更新验证程序。更新验证器根据模型的架构验证更新操作。setDefaultsOnInsert
:如果upsert
是true,则在创建新文档时,猫鼬将应用模型模式中指定的默认值。此选项仅在MongoDB> = 2.4上有效,因为它依赖于MongoDB的$setOnInsert
operator。rawResult
:如果为true,则返回MongoDB驱动程序的原始结果strict
:覆盖此更新的架构的严格模式选项