Tag Archives: mongoose

Find on different collections to create a document using mongoose

I need to query multiple collections to prepare a MongoDB document and then save it using Mongoose and NodeJS. The solution is to use async.parallel
I have two source collections, Robot, Target and the destination collection Activity.

For first, async must be added:

var async = require('async');

then:

async.parallel({
 
    robotFind: function(cb) { Robot.find({ "_id": jsonContent.robotId }).exec(cb); },
    targetFind: function(cb) { Target.find({ "_id": jsonContent.targetId }).exec(cb); }
 
}, function(err, result) {
 
    activity.robot = result.robotFind[0];
    activity.action = result.actionFind[0];
    activity.target = result.targetFind[0];
 
    activity.execution_date = jsonContent.execution_date;
    activity.alert = jsonContent.alert;
    activity.result = executionResult;
 
    activity.description = jsonContent.description;
 
    activity.save(function(err) {
        if (err) {
            console.log('[postActivity] ' + err)
            res.status(500).json({ error: err.message })
        } else {
            console.log('[postActivity] Saved!')
            res.status(200).json({ message: activity })
        }
    })
}

So, first part queries the MongoDB and fill the object result. Second part consumes result object, create the new document and save it.

PS: if you like it please, click on the banner :)

Tagged , ,