无法在用户对象(猫鼬)中保存消息 ID

Posted

技术标签:

【中文标题】无法在用户对象(猫鼬)中保存消息 ID【英文标题】:Unable to save message ID in user Object (Mongoose) 【发布时间】:2018-06-24 09:41:13 【问题描述】:

我的目标是使用 Mongoose 将消息推送到用户对象的消息属性(它是一个数组)中。但是,当我尝试保存用户 (user.save()) 时出现错误。我在下面的代码上做了这三个console.logs,看看出了什么问题。有人可以解决这个问题吗?

console.log(user.messages);
            user.messages.push(result._id);
            console.log(user.messages)

            user.save(function (err, result) 
                console.log(err)
            );

所以,在我将消息推送到数组之前,一个在我之后,一个在我尝试保存用户之后检查错误。这给了我以下日志:

首先,一个空数组 []

第二个,包含消息ID的数组

["5a5cdd894504771c80c8901a"]

三、没有正确保存用户的错误:

 MongoError: Unknown modifier: $pushAll
    at Function.MongoError.create (C:\Users\TijlD\Desktop\projects\03 MongoDB\node_modules\mongodb-core\lib\error.js:31:11)
    at toError (C:\Users\TijlD\Desktop\projects\03 MongoDB\node_modules\mongodb\lib\utils.js:139:22)
    at C:\Users\TijlD\Desktop\projects\03 MongoDB\node_modules\mongodb\lib\collection.js:1059:67
    at C:\Users\TijlD\Desktop\projects\03 MongoDB\node_modules\mongodb-core\lib\connection\pool.js:469:18
    at process._tickCallback (internal/process/next_tick.js:150:11)
  name: 'MongoError',
  message: 'Unknown modifier: $pushAll',
  driver: true,
  index: 0,
  code: 9,
  errmsg: 'Unknown modifier: $pushAll' 

这是服务器端的代码(node.js)

router.post('/', function (req,res,next)
        // We stored the user in the token so we can retrieve it from this token.
        // fetch the user (in the token) who reached this route


    // we use the jwt package to decode the token ( we wont be able to grab the user if we skip this step)
    // the decode method does not check if the token is valid, this happens
    // higher up in this file. we only decode it to grab the user. If we hadn't
    // protected our route we wouldve had to use a different strategy (.verify method)
    var decoded = jwt.decode(req.query.token);

    User.findById(decoded.user._id, function(err, user)

        if (err) 
            return res.status(500).json(
                title: 'An error occurred',
                error: err
            );
        
        var message = new Message(
            content: req.body.content,
            user: user._id
        );
        message.save(function(err, result) 

            if (err) 
                return res.status(500).json(
                    title: 'An error occurred',
                    error: err
                );
            
            console.log(user.messages);
            user.messages.push(result._id);
            console.log(user.messages)

            user.save(function (err, result) 
                console.log(err)
            );
            res.status(201).json(
                message: 'Saved message',
                // this object is what we'll receive in the front-end
                // and what we'll convert using the response.json() method
                obj: result
            );
        );
    );
);

这是用户模型

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mongooseUniqueValidator = require('mongoose-unique-validator');

var schema = new Schema(
    firstName: type: String, required: true,
    lastName: type: String, required: true,
    password: type: String, required: true,
    email: type: String, required: true, unique: true,
    messages: [type: Schema.Types.ObjectId, ref: 'Message']
);

schema.plugin(mongooseUniqueValidator);

module.exports = mongoose.model('User', schema);

【问题讨论】:

您使用的是哪个版本的猫鼬? 猫鼬版本 5.5.1 【参考方案1】:

根据this issue,$pushAll 已被弃用,您可以通过在架构选项中设置 usePushEach: true 来解决此问题

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mongooseUniqueValidator = require('mongoose-unique-validator');

var schema = new Schema(
    firstName: type: String, required: true,
    lastName: type: String, required: true,
    password: type: String, required: true,
    email: type: String, required: true, unique: true,
    messages: [type: Schema.Types.ObjectId, ref: 'Message']
,  usePushEach: true );

schema.plugin(mongooseUniqueValidator);

module.exports = mongoose.model('User', schema);

【讨论】:

以上是关于无法在用户对象(猫鼬)中保存消息 ID的主要内容,如果未能解决你的问题,请参考以下文章

猫鼬查询:在数组中按 id 查找对象

如何将json对象数组保存到猫鼬?

如何将json对象数组保存到猫鼬?

无法使用猫鼬推送到阵列

猫鼬模型静态/方法不保存“this”中的值

猫鼬模式中的加入/查找聚合