3

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

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

2 回答 2

1

您的ArticleSchema定义只需要正确声明其categorie属性类型(即 not Schema.ObjectIdbut 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'
    }
});
于 2015-09-10T03:10:19.950 回答
1

我认为这就是您要寻找的东西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. 您应该将您的参考架构提供给 es_schema 以进行正确的映射
  2. 默认情况下 mongoosastic 将索引整个模式。在您的架构上提供一个 es_select 字段以选择特定字段。
  3. populate 数组是您传递给 mongoose Model.populate 的相同选项的数组
于 2015-12-01T19:51:01.560 回答