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

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

问题描述

在Node.js中使用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".在您的情况下,您需要"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.

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

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