Mongoose强制转换错误 - 嵌入式子文档

时间:2015-11-07 16:15:59

标签: javascript mongodb mongoose

看看以下架构设计:

var message = new Schema({
  receivers: [User],
  message: String,
  owner: {
    type: Schema.Types.ObjectId,
    ref: 'User'
  }
});

var user = new Schema({
  name: String,
  photo: String
});

var inbox = new Schema({
  messages: [Message],
  owner: {
    type: Schema.Types.ObjectId,
    required: true
  },
  sequence: Number
});

当我尝试使用以下内容创建新消息时

var newMessage = {
  receivers: ['<id1>', '<id2>'],
  message: 'Hello world',
  owner: '<userId>'
}

Inbox.findOneAndUpdate({
  owner: '<userId>'
}, {
  $push: {
    messages: newMessage
  },
  $set: {
    sequence: '<sequence>'
  }
}, {
  upsert: true
}, callback);

它返回以下错误:

MongooseError.CastError "Cast to undefined failed for value [object Object] at path "messages""

我做错了什么?我怎样才能使它发挥作用?

感谢。

1 个答案:

答案 0 :(得分:1)

消息对象的receivers字段期望具有User模式的对象数组,而不是ObjectId's十六进制字符串表示的数组。因此,您需要将receivers数组替换为由id表示的实际对象,例如

var newMessage = {
    receivers: ['<id1>', '<id2>'],
    message: 'Hello world',
    owner: '<userId>'
};

Users.find({ "_id": {"$in": newMessage.receivers} }, function (err, users){
    // handle error
    if (err) throw err;

    // do the update
    newMessage.receivers = users;
    Inbox.findOneAndUpdate(
        { owner: '<userId>'}, 
        {  
            $push: { messages: newMessage  },
            $set: { sequence: '<sequence>' }
        }, 
        { upsert: true}, callback
    );
});