节点jsmongoose通过深层嵌套的文件find

在Node js mongoose中需要search以下模式级别的文章描述。 mongoose怎么可能呢? 我曾尝试使用$ elemMatch和它不工作。 架构级别如下。

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); 

我已经尝试如下,但它不工作。

 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); }); 

你可以尝试使用$regex$options

当你的条件是一个对象,那么就不需要使用{criteria}在查找中使用find(criteria 。如果subChapters:[chapterSchema]在你的agreementSchema那么使用subChapters.subChapters.Articles.description:在我的例子中使用的chapters.subChapters.Articles.description: subChapters.subChapters.Articles.description: chapters.subChapters.Articles.description:

当你想find嵌套的字段时,你应该使用""

 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); });