Querying for Object in Mongoose Sub Array

 ̄綄美尐妖づ 提交于 2021-01-28 18:43:16

问题


I have a Schema that looks like this:

var LibrarySchema = new Schema({
    id: String,
    contactNumber: String,
    collections: [{
        id: String,
        description: String
        subCollections: [{
            id: String,
            description: String,
            recentlyUpdated: Boolean
        }, {
            id: String,
            description: String,
            recentlyUpdated: Boolean
        }]
    }]
})

module.exports = mongoose.model('Library', LibrarySchema); 

All the ID's are unique. There can be multiple Libraries inside a District (another array).

My question is, how would I query into the nested arrays to get the desired object? To be more precise, how would I get a specific subCollection object, given a Library ID, Collection ID, and subCollection ID.


回答1:


You can use this query:

Library.find({
  'id': libraryID,
  'collections.id': CollectionID,
  'collections.subCollections.id': subCollectionID
}, { 'collections.subCollections.$': 1 }, function(err, data) {
  console.log(err, data);
})


来源:https://stackoverflow.com/questions/37666138/querying-for-object-in-mongoose-sub-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!