gpt4 book ai didi

javascript - 如何将返回值推送到数组 mongodb 中?

转载 作者:太空宇宙 更新时间:2023-11-04 01:10:59 25 4
gpt4 key购买 nike

我正在获取friendRequests的正确数据,该数据正在获取用户ID并将其放入 Mongoose 文件的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});

}

});
};

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

关于javascript - 如何将返回值推送到数组 mongodb 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17727758/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com