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

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

问题描述

当我尝试更改 Mongoose 查询返回的数据的任何部分时,它没有任何效果.

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

昨天我花了大约 2 个小时试图解决这个问题,使用各种 _.clone() s,使用临时存储变量等.最后,就在我想我要去的时候疯了,我找到了解决方案.所以我想将来有人(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 对象而不是完整的模型实例,您可以调用 lean() 像这样:

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.

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

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