Seltsam Seltsam - 5 months ago 15
Node.js Question

Augment queried object with another queried object

Trying to combine two result-objects from a mongoose query into one object.
Why is this not working? Any ideas how to make this work?

exports.get = function(req, res, err) {
Project.findOne({
_id: req.params.id
}, function(err, project) {
Client.findOne({
_id: project.clientId
}, function(err, client) {
project.foo = "bar" // works
project.client = client; // why is this not working?
res.send(project); // object has property "foo" but no property "client"
})
})
}

Answer

Mongoose documents don't allow adding properties. You need to either call the lean() method before exec() since documents returned from queries with the lean option enabled are plain javascript objects.

From the docs:

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

So your code should look like:

exports.get = function(req, res, err) {
    Project.findOne({ '_id': req.params.id })
           .lean()
           .exec(function(err, project) {
               Client.findOne({ '_id': project.clientId })
                     .lean()
                     .exec(function(err, client) {
                         project.foo = "bar" // works
                         project.client = client; // works
                         res.send(project); // object has both properties
                     });
           });
}

or cast the returned document to a plain JS object:

exports.get = function(req, res, err) {
    Project.findOne({
        _id: req.params.id
    }, function(err, project) {
        Client.findOne({
            _id: project.clientId
        }, function(err, client) {
            var obj = project.toObject();
            obj.foo = "bar" // works
            obj.client = client; // works
            res.send(obj); // object has both properties
        })
    })
}