Mongoose find result and then replace field findOne

I'm new to mongodb and came from a relational database, and I'm not joining in the good pain of getting me to keep working with mongodb.

What I want to archive here is to get all projects and update the projectType with the correct project type name, not the project type id. Either way, .attrubtes projects simply cannot be overwritten. then I tried the following entry. no luck. any help is appreciated. anyone can give me some guide, would be very grateful.

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

var _ = require('lodash');
var project = require('./project.model');
var Form = require('../form/form.model');

// Get list of projects
exports.index = function(req, res) {
  project.find(function (err, projects) {
    if(err) { return handleError(res, err); }

    _.each(projects, function(element, index){
      Form.findOne({_id : projects[index].projectType}, '-formContent -_id -createdDateTime', function(error, form){

        if(form !== undefined) projects[index].projectType = form.formName;
      });
    });

    return res.json(200, projects);
  }).sort({ createdDateTime: 'desc' });
};

      

+3


source to share


1 answer


Mongoose documents do not allow adding properties. You need to either call the methodbeforewhen documents are returned from requests with lean option enabled - they are plain javascript objects, or casts the returned document to plain object :. lean()

exec()

From the docs :

project.find().lean().exec(function (err, projects) {
    projects[0] instanceof mongoose.Document // false
});

      

So your code should look like this:



project.find()
    .lean()
    .exec(function (err, projects) {
        if(err) { return handleError(res, err); }

        _.each(projects, function(element, index){
            Form.findOne(
                {_id : projects[index].projectType}, 
                '-formContent -_id -createdDateTime', 
                function(error, form){
                    if(form !== undefined) projects[index].projectType = form.formName;
                }
            );
        });

        return res.json(200, projects);
    }).sort({ createdDateTime: 'desc' });

      

or cast the returned document to a plain object:

project.find()
    .exec(function (err, docs) {
        if(err) return res.send(err);
        var projects = [];
        _.each(docs, function(item, i) {
            var obj = item.toObject();
            Form.findOne(
                {_id : docs[i].projectType}, /* {_id : item.projectType} */
                '-formContent -_id -createdDateTime', 
                function(error, form){
                    if(form !== undefined) {
                        obj.projectType = form.formName;
                        projects.push(obj);
                    }
                }
            );
        });

        res.send(projects); 
    });

      

+3


source







All Articles