Monday 1 May 2017

Mongoose promise for .save() method

How can I return resolve() for successful save operation in mongoose (after that save operation)? I've tried to take promise for save, and then resolve in that code, but nothing happens

I use global promises for mongoose

var express = require('express');
var router = express.Router();

router.post('/', function(req, res, next) {


var roomModel = require('../../../models/room').roomModel;

roomModel.findOne({ name: req.body.roomName })
    .then(
        (room) => {
            return new Promise(function(resolve, reject) {
                //if no room present, create one, if present, check password
                if (room) {

                    if (room.password === req.body.roomPassword) {
                        return resolve({
                            code: 200,
                            message: 'Succesfully joined the room'
                        });
                    } else return reject({
                        code: 401,
                        message: 'Room password not correct'
                    });

                } else {
                    // create new room with given data
                    var newRoom = roomModel({});
                    newRoom.name = req.body.roomName;
                    newRoom.password = req.body.roomPassword;
                    newRoom.users = [req.body.userName];

                    return newRoom.save().then((err) => {
                        if (!err)
                            return resolve({
                                code: 200,
                                message: 'Room succesfully created'
                            });
                        else return reject({
                            code: 500,
                            message: 'Error when saving room'
                        });
                    });
                }
            });
        }
    )
    .then((status) => {
        // send regular response
        res.json({
            meta: {
                code: status.code,
                message: status.message
            },
            data: {}
        });
    })
    .catch(
        // Handle any errors and return them to user
        (err) => {
            console.log(err);
            res.json({
                meta: {
                    code: err.code,
                    message: err.message
                },
                data: {}
            });
        }
    );
});

module.exports = router;

To be more specific:

  1. How to take promise for .save() mongoose method?
  2. How to return resolve/reject in that inner promise, for outer promise, that also returns resolve/reject for another .then operation


via Jakub Pastuszuk

No comments:

Post a Comment