如何将返回值推入数组mongodb?

我得到正确的数据为friendRequests获取用户ID并将其引入我的mongoose文件的friendRequest字段中。 当我添加$ push将数据添加到路由文件中的friendRequest数组中时,它实际上不会插入它,并将我创build的err函数返回给我。

这是我的路线文件:

exports.addContactPost = function(req, res, err) { User.findByIdAndUpdate(req.signedCookies.userid, { $push: {friendRequest: req.body.friendRequest} }, function(err) { if(err) { console.log("post2"); return console.log('error'); } else { console.log('postsuccess'); res.json({response: true}); } }); }; 

这里是mongoose文件:

 var mongoose = require('mongoose'), Schema = mongoose.Schema, bcrypt = require('bcrypt-nodejs'), SALT_WORK_FACTOR = 10; var UserSchema = new Schema({ email: { type: String, required: true, lowercase:true, index: { unique: true } }, password: { type: String, required: true }, firstName: {type: String, required: true}, lastName: {type: String, required: true}, phone: {type: Number, required: true}, birthday: {type: Date, required: true}, friendRequest: {type: Array}, friend: {type: Array} }); UserSchema.pre('save', function(next) { var user = this; console.log("email exists"); // only hash the password if it has been modified (or is new) if (!user.isModified('password')) return next(); // generate a salt bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) { if (err) return next(err); // hash the password along with our new salt bcrypt.hash(user.password, salt, null, function(err, hash) { if (err) return next(err); // override the cleartext password with the hashed one user.password = hash; next(); }); }); }); UserSchema.methods.comparePassword = function(candidatePassword, cb) { bcrypt.compare(candidatePassword, this.password, function(err, isMatch) { if (err) return cb(err); cb(null, isMatch); }); }; module.exports = mongoose.model('User', UserSchema); 

所以mongo发现与提供的userId相匹配的文档没有数组作为它的friendRequest属性。 在mongo shell中通过ID来查看这个特定的文档,并且修复它以使friendRequest是一个数组。