在Elasticsearch的搜索中包含ObjectId



我使用ElasticSearch和mongoosastic来同步MongoDB和ElasticSearch之间的数据。我想包括一个模式的属性,这是我的研究中的另一个对象:我想显示的文章有我正在搜索的类别。这是我的两个模式:articlesschema和CategorySchema。文章包含一个名为" Category "的Category对象。

var ArticleSchema = new Schema({
    created: {
        type: Date,
        default: Date.now
    },
    ...
    user: {
        type: Schema.ObjectId,
        ref: 'User'
    },
    categorie: {
        type: Schema.ObjectId,
        es_indexed:true,
        ref: 'Category',
        required: 'Le champ "Categorie" ne peut pas etre vide'
    }
});
var CategorySchema = new Schema({
    name: {
        type: String,
        default: '',
        required: 'Please fill Category name',
        trim: true
    },
    ...
    niveau: {
        type: Number
    }
});

您的ArticleSchema定义只需要正确声明其categorie属性类型(即不是Schema.ObjectId而是CategorySchema)。

如mongoosastic文档中嵌套模型所示,您可以这样做:

var ArticleSchema = new Schema({
    ...
    categorie: {
        type: [CategorySchema],        <--- change the type to this
        es_indexed:true,
        ref: 'Category',
        required: 'Le champ "Categorie" ne peut pas etre vide'
    }
});

我想这就是你要找的https://github.com/mongoosastic/mongoosastic/pull/118

var Comment = new Schema({
    title: String,
    body: String,
    author: String
});

var User = new Schema({
    name: {type:String, es_indexed:true},
    email: String,
    city: String,
    comments: {type: Schema.Types.ObjectId, ref: 'Comment', es_schema: Comment, es_indexed:true, es_select: 'title body'}
})
User.plugin(mongoosastic, {
    populate: [
        {path: 'comments', select: 'title body'}
    ]
})

事项:

  1. 你应该提供你的refschema给es_schema,以便做出正确的映射
  2. 默认情况下mongoosastic将索引整个模式。在你的模式上提供一个es_select字段来选择特定的字段。
  3. 填充数组是一个与传递给mongoose的相同选项的数组。

最新更新