node js mongoose通过深层嵌套文档查找

时间:2016-12-22 10:56:47

标签: node.js mongodb mongoose

在Node js 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);
    }); 

1 个答案:

答案 0 :(得分:2)

您可以尝试使用$regex$options

当您的条件是对象时,无需使用{criteria}查找只使用find(criteria。 如果subChapters:[chapterSchema]中有agreementSchema,请在我使用subChapters.subChapters.Articles.description:的示例中使用chapters.subChapters.Articles.description:

并且在想要查找嵌套字段时应使用""

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