猫鼬查询结果是只读的吗? [英] Is Mongoose query result read-only?

查看:75
本文介绍了猫鼬查询结果是只读的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何修改猫鼬查询返回的对象?

How can I modify an object returned by a Mongoose query?

假设我们具有以下架构:

Assume we have the following schema:

var S = new mongoose.Schema( { 'name': String, 'field': String } );

我对结果进行以下查询和修改:

I do the following query and modification to the result:

var retrieve = function(name, callback) {
    S.findOne({ name: name }).exec(function (err, obj) {
      if (err) return handleError(err);
      obj['field'] = 'blah';
      callback(obj);
    });
}

obj.field将不包含blah,而是查询返回的原始值,就好像它是只读的一样.发生了什么事?

The obj.field will not contain blah but the original value returned by the query, as if it was read-only. What is going on?

注意:我的环境是Node.js,Express,Mongoose和MongoDB

Note: my environment is Node.js, Express, Mongoose and MongoDB

推荐答案

注意:这是一个编辑,我的原始答案与众不同

Note: This is an edit, my original answer was rather different

所以这有点令人困惑,但是 Mongoose返回MongooseDocument对象,而不是普通的JSON对象.因此,请在obj上使用.lean()方法,该方法会将其转换为JSON,然后从那里开始根据需要进行更改.

So this is a little confusing but Mongoose returns MongooseDocument objects and not plain JSON objects. So use the .lean() method on obj which will turn it into JSON, and from there you start altering it as you wish.

感谢Ze Jibe.

这篇关于猫鼬查询结果是只读的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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