简体   繁体   English

仅在数组中进行特定查询时才获取和更新文档?

[英]Get and update document only when specific query in array?

I have some trouble with my mongoose request ! 我的猫鼬请求有些麻烦!

Here is my model : 这是我的模型:

var MessageSchema = new Schema({

...,

messages: [
    {
        user: {
            type: Schema.ObjectId,
            ref: 'User'
        },
        created: {
            type: Date,
            default: Date.now
        },
        content: String,
        readBy: [{
            type: Schema.ObjectId,
            ref: 'User'
        }]
    }
]});

With this, I have to know how many new messages I have ! 有了这个,我必须知道我有多少新消息!

This is what I have done so far: 到目前为止,这是我所做的:

    Message.find({
        ...
    })
    .select('messages.readBy')
    .exec(function(err, messages) {
        if (err) {
            // catch error
        } else {
            // On trie les messages.
            _.forEach(messages, function(msgs,i){
                var allRead = true;
                _.forEach(msgs.messages, function(msg){
                    if(msg.readBy.indexOf(id) === -1){ allRead = false; }
                });
                if(allRead) messages = _.without(messages,messages[i]);
            });

            return $socket.emit('Messages:nbNonLu', messages.length);
        }
});

But I think this will be hard for the server when we'll have lots of messages. 但是我认为,当我们收到大量消息时,这对于服务器而言将是困难的。 Is it possible to get the same result with one request ? 一个请求能否获得相同的结果? ( get all documents where messages[] does not contain a specific userId . (获取所有所有messages[]不包含特定userId文档。

Then is it possible to update a document - push a userId in readBy array for all messages[] ? 然后是否可以更新文档-将readBy数组中的userId推送给所有messages[]

Message.find({'messages.readBy':{'$ne':id}},
       function(err,messages){
        //messages contain all messages whose readBy field does not contain the
        //specified user 
 })

To push userId in readBy to all messages 将readBy中的userId推送到所有消息

Message.update({},{'$addToSet':{'messages.readBy':userId}},{multi:true},function(err,num){
        //callback
        //Add a query in the first parameter({}) if needed
})

multi:true is used to update multiple documents. multi:true用于更新多个文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM