简体   繁体   中英

How to push returned value into an array mongodb?

I am getting the correct data for friendRequests which is getting a user ID and throwing it in the friendRequest field of my mongoose file. When I add $push to add the data into the friendRequest array in the route file, it actually does not insert it and gives me back the err function I created.

Here is my route file:

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});

                }

            });
};

Here is the mongoose file:

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);

So the document that mongo finds matching the provided userId does not have an array as its friendRequest property. Look at that specific document by ID in mongo shell and fix it so that friendRequest is an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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