node.js 为什么不能修改 Mongoose 查询返回的数据(例如:findById)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14504385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why can't you modify the data returned by a Mongoose Query (ex: findById)
提问by Toli
When I try to change any part of the data returned by a Mongoose Query it has no effect.
当我尝试更改 Mongoose 查询返回的数据的任何部分时,它不起作用。
I was trying to figure this out for about 2 hours yesterday, with all kinds of _.clone()s, using temporary storage variables, etc. Finally, just when I though I was going crazy, I found a solution. So I figured somebody in the future (fyuuuture!) might have the save issue.
我昨天花了大约 2 个小时试图解决这个问题,各种_.clone()s,使用临时存储变量等。最后,就在我快疯了的时候,我找到了一个解决方案。所以我想将来有人(fyuuuture!)可能会有保存问题。
Survey.findById(req.params.id, function(err, data){
var len = data.survey_questions.length;
var counter = 0;
_.each(data.survey_questions, function(sq){
Question.findById(sq.question, function(err, q){
sq.question = q; //has no effect
if(++counter == len) {
res.send(data);
}
});
});
});
回答by JohnnyHK
For cases like this where you want a plain JS object instead of a full model instance, you can call lean()on the query chain like so:
对于这样的情况,你想要一个普通的 JS 对象而不是一个完整的模型实例,你可以lean()像这样调用查询链:
Survey.findById(req.params.id).lean().exec(function(err, data){
var len = data.survey_questions.length;
var counter = 0;
_.each(data.survey_questions, function(sq){
Question.findById(sq.question, function(err, q){
sq.question = q;
if(++counter == len) {
res.send(data);
}
});
});
});
This way datais already a plain JS object you can manipulate as you need to.
这种方式data已经是一个普通的 JS 对象,您可以根据需要进行操作。
回答by Toli
I think the Mongoose documentation doesn't make this clear enough, but the data returned in the query (although you can res.send() it) is actually a Mongoose Document object, and NOT a JSON object. But you can fix this with one line...
我认为 Mongoose 文档并没有说清楚这一点,但查询中返回的数据(虽然你可以 res.send() 它)实际上是一个 Mongoose Document 对象,而不是一个 JSON 对象。但是你可以用一行来解决这个问题......
Survey.findById(req.params.id, function(err, data){
var len = data.survey_questions.length;
var counter = 0;
var data = data.toJSON(); //turns it into JSON YAY!
_.each(data.survey_questions, function(sq){
Question.findById(sq.question, function(err, q){
sq.question = q;
if(++counter == len) {
res.send(data);
}
});
});
});

