Mongoose 返回的数据是不可变的吗? [英] Is data returned from Mongoose immutable?
问题描述
我想添加到来自猫鼬查询的返回数据:
I want to add to the return data from a mongoose query:
User.findById(userId, function(err, data) {
if (!err) {
data.newvar = 'Hello, world';
}
});
但是,当我控制台记录输出时,newvar 不存在.我也尝试过使用 Underscore 的扩展:
However, when I console log the output, the newvar does not exist. I've also tried this using Underscore's extend:
_.extend(data, {'newvar': 'Hello, world'});
也没有运气.因为我有嵌套文档,所以使用浅拷贝是行不通的.有什么办法可以在这里追加数据吗?
With no luck either. Since I have nested documents, using a shallow copy won't work. Is there any way to append data here?
推荐答案
处理此问题的一种方法是通过调用 toObject()
就可以了:
One way to handle this is to convert your mongoose model instance into a plain object that you have full control over by calling toObject()
on it:
User.findById(userId, function(err, data) {
if (!err) {
data = data.toObject();
data.newvar = 'Hello, world';
}
});
如果您想要更结构化的解决方案,您可以按照此处的说明向架构添加虚拟属性.
If you want a more structured solution, you can add virtual attributes to your schema as described here.
这篇关于Mongoose 返回的数据是不可变的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!