最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Mongoose find in array of objects - Stack Overflow

programmeradmin2浏览0评论

I have a Mongoose schema

var MessageSchema = new Schema({
    streamer: {
        streamer_username: String,
        streams: [{
            id: String,
            messages: [{
                date: String,
                username: String,
                message: String,
                song: String
            }]
        }]
    }
})

It contains an array "streams", which contains objects that have the "id" value, as you can see. I'm trying to search the DB with this query.

MsgSchema.find({ "streamer.streamer_username" : streamer_name, "streamer.streams": { "$in": {id: response.data[0].id} }}, (err, found) =>{}})

But i find nothing. Even if i remove the first "username" part, it still doesn't find anything and returns an empty array, so the problem is clearly the second part. What is wrong with my query? I can't find anything about it in the documentation.

I have a Mongoose schema

var MessageSchema = new Schema({
    streamer: {
        streamer_username: String,
        streams: [{
            id: String,
            messages: [{
                date: String,
                username: String,
                message: String,
                song: String
            }]
        }]
    }
})

It contains an array "streams", which contains objects that have the "id" value, as you can see. I'm trying to search the DB with this query.

MsgSchema.find({ "streamer.streamer_username" : streamer_name, "streamer.streams": { "$in": {id: response.data[0].id} }}, (err, found) =>{}})

But i find nothing. Even if i remove the first "username" part, it still doesn't find anything and returns an empty array, so the problem is clearly the second part. What is wrong with my query? I can't find anything about it in the documentation.

Share Improve this question edited Oct 24, 2018 at 8:03 Jack 3,05711 gold badges50 silver badges69 bronze badges asked Oct 24, 2018 at 7:47 almarcalmarc 1,6583 gold badges14 silver badges32 bronze badges 2
  • 2 Read the docs docs.mongodb./manual/tutorial/query-array-of-documents – chridam Commented Oct 24, 2018 at 7:50
  • MsgSchema.find({ "streamer.streamer_username" : streamer_name, "streamer.streams.id": {"$in": response.data[0].id}}, (err, found) =>{}}) Worked. Thank you. – almarc Commented Oct 24, 2018 at 7:58
Add a ment  | 

1 Answer 1

Reset to default 4

I am late but I hope it helps other people

You can simply use .find() and inside it, you can create the specifications of the conditions on more than one field nested in an array of documents. The easiest way is:

MessageSchema.find({ "streamer.streams": { id: "XXX" } });
发布评论

评论列表(0)

  1. 暂无评论