猫鼬选择字段从findOneAndUpdate返回

编程入门 行业动态 更新时间:2024-10-19 02:19:55
本文介绍了猫鼬选择字段从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返回

本文发布于:2023-11-22 13:32:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617610.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   findOneAndUpdate

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!