简体   繁体   English

ZCCADCDEDB567ABAE643E15DCF0974E503Z:通过数组字段中的值查找文档

[英]Mongoose: find document by values inside an array field

I've got a chat schema that looks like that:我有一个看起来像这样的聊天模式:

var chatSchema = new mongoose.Schema({
    users: [{
        type: mongoose.Schema.Types.ObjectId,
        required: true
    }]
});

It contains array of user IDs.它包含一组用户 ID。 Now I want to find one chat document that contains an array of two user IDs.现在我想找到一个包含两个用户 ID 数组的聊天文档。

At the beginning I tried to do this:一开始我尝试这样做:

Chat.findOne({ users: { $in: [req.user_id, receiver._id] }})
    .then(chat => { })

But it seems that every time it gives me the chat that contains at least one of the IDs I mentioned in the query.但似乎每次它都会给我包含至少一个我在查询中提到的 ID 的聊天。

So I've tried to change it to this but with no luck:所以我试图把它改成这样,但没有运气:

Chat.findOne()
    .where({ users: { $in: [req.user_id] }})
    .where({ users: { $in: [receiver._id] }})
    .then(chat => { })

I need to find the chat that contains both of the user ID's inside the users array otherwise I expect for a null value.我需要在 users 数组中找到包含两个用户 ID 的聊天,否则我期望 null 值。

How can I achieve this goal?我怎样才能实现这个目标?

Thanks!谢谢!

This is the way $in works - returns the document when at least one value matches.这就是$in工作方式 - 当至少一个值匹配时返回文档。 You should use $all instead:你应该使用$all代替:

Chat.findOne({ users: { $all: [req.user_id, receiver._id] }})

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

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