Mongoose 选择要从 findOneAndUpdate 返回的字段 [英] Mongoose select fields to return from findOneAndUpdate

查看:66
本文介绍了Mongoose 选择要从 findOneAndUpdate 返回的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Nodejs 中使用 Mongoose,您可以使用 find 返回一些字段.例如.

Using Mongoose in Nodejs you can return some fields using find. eg.

User.findOne({_id:'132324'}, {first_name:1, last_name:1}).exec...

但我似乎无法弄清楚如何使用 findOneAndUpdate 返回某些字段.

but I can't seem to figure out how to return certain fields using findOneAndUpdate.

User.findOneAndUpdate({_id:'132324'}, {$set : {..bla bla}}, {first_name:1, last_name:1}).exec....

有没有人以前实现过这个?我在文档中找不到它.

Has anyone achieved this before? I can't find it in the documentation.

推荐答案

来自手册options 参数需要一个 "fields" 键,因为还有其他细节,例如 "upsert"新" 适用于此.在您的情况下,您需要 "new" 选项:

From the manual, the options argument needs a "fields" key in it since there are other details such as "upsert" and "new" where this applies. In your case you also want the "new" option:

User.findOneAndUpdate(
  { "_id": "132324" },
  { "$set": { "hair_color": "yellow" } },
  {
   "fields": { "first_name":1, "last_name": 1 },
   "new": true 
  }
).exec(...)

或者您可以使用 .select()

Alternately you may use .select()

User.select({ "first_name": 1, "last_name": 1 }).findOneAndUpdate(
  { "_id": "132324" },
  { "$set": { "hair_color": "yellow" } },
  { "new": true }
).exec(...)

请注意,如果没有 "new": true,返回的文档处于更新修改处理之前 的状态.有时这就是您的意思,但大多数时候您确实想要修改后的文档.

Noting that without "new": true the document returned is in the state before the modification of the update was processed. Some times this is what you mean, but most of the time you really want the modified document.

这篇关于Mongoose 选择要从 findOneAndUpdate 返回的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆