Mongoose/MongoDB-使用预定义架构附加到文档对象数组的简单示例 [英] Mongoose / MongoDB - Simple example of appending to a document object array, with a pre-defined schema

查看:56
本文介绍了Mongoose/MongoDB-使用预定义架构附加到文档对象数组的简单示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为简单起见,假设这些是我的收集模式:

For the sakes of simplicity, assuming these are my collection schemas:

var MessageDeliverySchema = new Schema({
    from   : { type : String },
    to     : { type : String },
    status : { type : String }
});

var Messages = mongoose.model('messages',
new Schema({
    id              : ObjectId,
    user            : { type:String },
    'sent-messages' : [MessageDeliverySchema]
}));

因此,集合 Messages 中的每个文档可能都有由MessageDeliverySchema定义的4/5 已发送消息.

So each document in the collection Messages may have 4/5 sent-messages defined by the MessageDeliverySchema.

我想做的是有一个已发送消息数组,因此每次收到收据时,我都只更新 Messages 并附加另一条已发送的消息.

What I want to do is have an array of sent-messages, so each time a delivery receipt comes in I just update Messages and append another sent message.

我尝试过的事情:

var delivered = {
from: 'foo',
to: 'bar',
status: 'delivered'
};

Message.update({_id: '5064aae4154cb34d14000001' },
        {$pushAll: { 'sent-messages' : delivered }} , {upsert:true}, function(err, data) { 

});

Message.update({_id: '5064aae4154cb34d14000001' },
         {$push: { 'sent-messages' : delivered }},{upsert:true}, function(err, data) { 
});

$ pushAll和$ push不会将新对象附加到已发送消息,而是会覆盖现有消息.

$pushAll, and $push, doesn't append a new object to sent-messages, instead it overwrites an existing message.

我想看到的是一系列已发送的消息,例如:

What I want to see is an array of sent messages e.g:

{
    'sent-messages': [
        {
            from: 'foo',
            to: 'bar',
            status: 'delivered'
        },
        {
            from: 'pippo',
            to: 'pippo',
            status: 'delivered'
        },
        {
            from: 'paul',
            to: 'smith',
            status: 'undelivered'
        }
    ]
}

推荐答案

我得到的错误是:'无法将$ push/$ pushAll修饰符应用于非数组'.

The error I was getting was: 'Cannot apply $push/$pushAll modifier to non-array'.

我向文档中添加了一个对象,如下所示:

I added an object to the document like this:

    Message.update({_id: '5064aae4154cb34d14000001' },
           { 'sent-messages' : delivered }, function(err, data) { 
    });

然后尝试执行$ push,这给了我上面的错误.

And then tried to do a $push, which gave me the above error.

所以我删除了文档,并使用了具有预期效果的$ push.

So I removed the document and used $push which had the desired effect.

作为参考,这是附加到现有文档的正确方法,也是对我的问题的回答:

For reference this is the correct way to append to an existing document, and the answer to my question:

Message.update({_id: '5064aae4154cb34d14000001' },
         {$push: { 'sent-messages' : delivered }},{upsert:true}, function(err, data) { 
});

这篇关于Mongoose/MongoDB-使用预定义架构附加到文档对象数组的简单示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆