and query mongoose example

Example 1: findbyid mongoose

// Find the adventure with the given `id`, or `null` if not found
await Adventure.findById(id).exec();

// using callback
Adventure.findById(id, function (err, adventure) {});

// select only the adventures name and length
await Adventure.findById(id, 'name length').exec();

Example 2: mongoose query with function(req, res, next)

router.post('/travellers',
    passport.authenticate('jwt', { "session": false }), function(req, res, next) {
    var pickup_location = req.body.pickup_location;
    var delivery_location = req.body.delivery_location;
    var date = req.body.date;
    var sender = req.user._id;
    var locals = {
        travellers: [],
        senders: []
    };

    async.series([
        // Load travels first
        function(callback) {
            Travel.find({ "date": date }, function (err, travels) {
                if (err) return callback(err);
                locals.travels = travels;
                callback();
            });
        },
        // Load users (won't be called before task 1's "task callback" has been called)
        function(callback) {
            async.forEach(locals.travels, function (travel, callback) {
                User.findById(travel.traveller, function (err, user) {
                    if (err) return callback(err);
                    data = {
                        "name": user.name,
                        "email": user.email,
                        "phone": user.phone,
                        "image_url": user.image_url,
                        "type": "traveller"
                    };
                    console.log(data);
                    local.travellers.push(data);
                    callback();
                });
            }, function (err) {
                if (err) return callback(err);
                            callback();
            });
        }
    ], function(err) { /* This function gets called after 
          the two tasks have called their "task callbacks" */
        if (err) return next(err);
        //Here locals will be populated with `travellers` and `senders`
        //Just like in the previous example
        console.log(locals);
        console.log(locals.travellers);
        res.json(locals.travellers);
    });
});

Tags:

Misc Example