Why can't you modify the data returned by a Mongoose Query (ex: findById)

前端 未结 2 1082
青春惊慌失措
青春惊慌失措 2020-11-22 06:51

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

I was trying to figure this out for about 2 hours yesterday, with all kinds

2条回答
  •  忘了有多久
    2020-11-22 07:07

    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...

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

提交回复
热议问题