Express,Mongoose - .update()返回null

时间:2017-05-29 16:35:47

标签: javascript node.js express mongoose

当我尝试更新模型中的文档时,.update()返回null但.find()方法工作正常。

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 = { $set: objForUpdate }
      , options = { multi: true };

    //This throws error
    // Error: { ok: 0, n: 0, nModified: 0 }
    Profile.update(conditions, setObj, (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." });
        });
    }); */
};

// API端点

http://localhost:3000/api/v1/profile/592c53b3bdf350ce004ad717/updatebio

// API定义

'use strict';

/** 
 * Routes for Profile Model
 *
 **/

var passport     = require('passport');
var jwt          = require('jwt-simple');
var settings     = require("settings");

var profileCtrl    = require(settings.PROJECT_DIR + 'routes/controllers/api/profile');

module.exports = function(app) {
    app.get('/all',                 profileCtrl.getAll);
    app.get('/:id',                 profileCtrl.getSingle);
    app.put('/:id/updateurl',       profileCtrl.updateURL);
    app.put('/:id/updateaddress',   profileCtrl.updateAddress);
    app.put('/:id/updatebio',       profileCtrl.updateBio);
}

//型号

var mongoose = require('mongoose');

// User Schema

var ProfileSchema = mongoose.Schema({
    url : {
        type: String,
        unique: true,
    },
    fname: {
        type: String,
        required: true
    },
    lname: {
        type: String,
        required: true
    },
    email: { 
        type: String,
        unique: true,
        required: true
    },
    bio: {
        profile_picture: {
            type: String
        },
        title: {
            type: String
        },
        intro: {
            type: String
        },
        summary: {
            type: String
        },
        skills: {
            type: Object
        },
        social: {
            linkedin: {
                type: String
            },
            twitter: {
                type: String
            },
            facebook: {
                type: String
            },
            website: {
                type: String
            }
        },
    },
    location: {
        address: {
            type: String
        },
        apt: {
            type: String
        },
        city: {
            type: String
        },
        state: {
            type: String
        },
        zip_code: {
            type: String
        },
        country: {
            type: String
        }
    },
    phone: {
        type: Number
    },
    listings: {
        type: Object
    },
    reviews: {
        type: Object
    },
    verfied: {
        type: Boolean,
        default: false
    },
    // expires: { 
    //  type: Date, 
    //  expires: '1h', 
    //  default: Date.now 
    // },
});

var Profile   = module.exports = mongoose.model('Profile', ProfileSchema);

module.exports.getUserByEmail = function(email, callback){
    var query = {'email': email};

    Profile.findOne(query, callback);
}

module.exports.checkIfUrlExists = function(res, url, callback){
    var query = {'url': url};

    Profile.findOne(query, function(error, found) {
        if(error) return res.status(500).json(error);
        if(found) return res.status(500).json({success: false, message: "URL already exists" });

        if(callback) callback();
    });
}

//我想要更新的文件

{
  "_id": "592c53b3bdf350ce004ad717",
  "url": "hyoh7ryb-",
  "fname": "Foo",
  "lname": "Bar",
  "email": "foobar@gmail.com",
  "__v": 0,
  "verfied": false
}

1 个答案:

答案 0 :(得分:1)

未保存架构中未定义的任何内容。当您在准备bioobjForUpdate时丢失$set密钥时,会发生这种情况:

var objForUpdate = {};
if (!troolr.isEmptyString(req.body.profile_picture))  objForUpdate.profile_picture = req.body.profile_picture;

应该是

var objForUpdate = {
   bio: {}
};
if (!troolr.isEmptyString(req.body.profile_picture))  objForUpdate.bio.profile_picture = req.body.profile_picture;
if (!troolr.isEmptyString(req.body.title))           objForUpdate.bio.title = req.body.title;
// and so on

您的save正在运行,因为将对象保存在右键user.bio = objForUpdate;