Monday, 29 May 2017

Express, Mongoose - .update() is returning null

When I am trying to update a document in my model, the .update() is returning null but the .find() method works fine.

module.exports.updateBio = function(req, res) {
    var userID = req.params.id;
    var objForUpdate = {};

    if (!troolr.isEmptyString(req.body.profile_picture)) objForUpdate.profile_picture = req.body.profile_picture;
    if (!troolr.isEmptyString(req.body.title))           objForUpdate.title = req.body.title;
    if (!troolr.isEmptyString(req.body.intro))           objForUpdate.intro = req.body.intro;
    if (!troolr.isEmptyString(req.body.summary))         objForUpdate.summary = req.body.summary;   
    if (!troolr.isEmptyString(req.body.skills))          objForUpdate.skills = req.body.skills;
    if (!troolr.isEmptyString(req.body.facebook))        objForUpdate.social.facebook = req.body.facebook;
    if (!troolr.isEmptyString(req.body.twitter))         objForUpdate.social.twitter = req.body.twitter;
    if (!troolr.isEmptyString(req.body.linkedin))                                objForUpdate.social.linkedin = req.body.linkedin;
    if (!troolr.isEmptyString(req.body.website))                                 objForUpdate.social.website = req.body.website;

    var conditions = { "_id": userID }
      , setObj = { $setOnInsert: objForUpdate }
      , options = { multi: true };

    //This throws error
    // Error: { ok: 0, n: 0, nModified: 0 }
    Profile.update(conditions, objForUpdate, (err, page) =>{
        if(err) throw err;
        console.log(page);
    });

    // This works fine but it erases old values if they are empty
    /* Profile.findById(userID, (error, user) => {
        if(error) return res.status(500).json({ success: false, error: error });

        user.bio = objForUpdate;

        user.save(function(error) {
            if(error) return res.status(500).json({ success: false, error: error });

            return res.status(200).json({ success: true, message: "Bio successfully updated." });
        });
    }); */
};



via Shivam

No comments:

Post a Comment