【问题标题】:How to push returned value into an array mongodb?如何将返回值推入数组 mongodb?
【发布时间】:2013-07-18 23:37:54
【问题描述】:

我正在获取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});

                }

            });
};

这里是猫鼬文件:

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

【问题讨论】:

  • err 参数包含哪些错误消息?
  • MongoError: 无法将 $push/$pushAll 修饰符应用于非数组

标签: javascript node.js mongodb mongoose


【解决方案1】:

因此,mongo 找到的与提供的 userId 匹配的文档没有数组作为其 friendRequest 属性。在 mongo shell 中按 ID 查看该特定文档并修复它,以便 friendRequest 是一个数组。

【讨论】:

  • 对不起,你能举个例子吗,我想我明白了,但我仍然有问题。我想我必须做的是进入猫鼬UserSchema并更改friendRequest:[String],就像那样或什么?但我仍然得到错误,除非我做错了
  • 不是代码问题。这是您的 mongo 数据库中的数据的 DATA 问题。或者,特别是您的代码期望存在的数据与实际存在的数据之间的不匹配。去看看你的数据库中的那个特定记录,你会发现friendRequest 不是一个数组。
  • 谢谢,对不起,是的,我没有意识到我正在测试的帐户是在将新的数组类型属性添加到帐户之前创建的!对此感到抱歉。
猜你喜欢
  • 1970-01-01
  • 2013-06-04
  • 2021-05-23
  • 2018-07-26
  • 1970-01-01
  • 2012-06-27
  • 1970-01-01
  • 2020-03-23
相关资源
最近更新 更多