简体   繁体   中英

node js mongoose find by deeply nested documents

In Node js mongoose Need to search the article description in following schema levels. how can it be possible with mongoose. I have tried using $elemMatch and its not working. schema level is as follows.

var articleSchema = new Schema({
    name: { type: String, required: true },
    displayName: { type: String },
    description: { type: String },

});

mongoose.model('Article', articleSchema);   

var subChapterSchema = new Schema({
    name: {type: String, required: true},
    displayName: {type: String},
    Articles:[articleSchema],


});

mongoose.model('SubChapter', subChapterSchema); 

var chapterSchema = new Schema({
    name: {type: String, required: true },
    displayName: {type: String },
    subChapters: [subChapterSchema],

});

mongoose.model('Chapter', chapterSchema);

var agreementSchema = new Schema({
    name: {type: String, required: true },
    displayName: {type: String },
    Chapters: [chapterSchema],

});

mongoose.model('Agreement', agreementSchema);

I have tried as follows.but its not working.

var regex = new RegExp(text, "i");

    var criteria = { 
    Chapters.subChapters.Articles : {
                                                    $elemMatch: {
                                                        description:regex
                                                    }
                                                  }
                                        }

Agreement.find({criteria},'name displayName',function(err,docs){
        if (err)
            console.log('error occured in the database');
        console.log(docs);
    }); 

You can try with $regex and $options .

When your criteria is an object then no need to use {criteria} in find just use find(criteria . If subChapters:[chapterSchema] in your agreementSchema then use subChapters.subChapters.Articles.description: in my example used chapters.subChapters.Articles.description: .

and you should use "" when want to find nested field

var text = 'search text';

var criteria = {
  "chapters.subChapters.Articles.description": { $regex: text, $options: 'i' }
};

Agreement.find(criteria, 'name displayName', function (err, docs) {
  if (err)
    console.log('error occured in the database');
  console.log(docs);
}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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