为什么不能修改猫鼬查询返回的数据(例如:findById) [英] Why can't you modify the data returned by a Mongoose Query (ex: findById)

查看:76
本文介绍了为什么不能修改猫鼬查询返回的数据(例如:findById)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试更改猫鼬查询返回的数据的任何部分时,它均无效.

When I try to change any part of the data returned by a Mongoose Query it has no effect.

昨天我尝试使用各种_.clone(),使用临时存储变量等来解决这个问题大约2个小时.最后,就在我发疯的时候,我找到了解决方案.所以我想以后有人(fyuuuture!)可能会遇到保存问题.

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.

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);
            }
        });
    });
});

推荐答案

对于像这样的情况,如果您希望使用纯JS对象而不是完整的模型实例,则可以调用

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:

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);
            }
        });
    });
});

这种方式data已经是一个普通的JS对象,您可以根据需要对其进行操作.

This way data is already a plain JS object you can manipulate as you need to.

这篇关于为什么不能修改猫鼬查询返回的数据(例如:findById)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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