繁体   English   中英

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

[英]How to push returned value into an array mongodb?

我正在为friendRequests获取正确的数据,该数据正在获取用户ID并将其扔到我的猫鼬文件的friendRequest字段中。 当我添加$ push以将数据添加到路由文件中的friendRequest数组中时,它实际上并未插入数据,并向我返回了我创建的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});

                }

            });
};

这是猫鼬文件:

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是一个数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM