如何在mongoosastic中将嵌套文档作为对象

时间:2016-01-30 09:33:13

标签: node.js mongodb elasticsearch mongoose mongoosastic

我有一个带有mongoosastic的nodejs服务器试图将嵌套的搜索结果作为对象而不是仅仅索引。

那是我的代码:

require('../server/serverInit');


var elasticsearch = require('elasticsearch');
var esclient = new elasticsearch.Client({
    host: 'localhost:9200',
    log: 'trace'
});


var Schema = mongoose.Schema;
var mongoosastic = require('mongoosastic');

var elasticsearch = require('elasticsearch');
var esclient = new elasticsearch.Client({
    host: '127.0.0.1:9200',
    log: 'trace'
});
global.DBModel = {};
/**
 * StoreSchema
 * @type type
 */

var storeSchema = global.mongoose.Schema({
    Name: {type: String, es_indexed: true},
    Email: {type: String, es_indexed: true},
   .....
    _articles: {type: [articleSchema],
        es_indexed: true,
        es_type: 'nested',
        es_include_in_parent: true}
});

/**
 * ArtikelSchema
 * @type Schema
 */

var articleSchema = new Schema({       
    Name: {type: String, es_indexed: true},
    Kategorie: String,
    ....
    _stores: {type: [storeSchema],
        es_indexed: true,
        es_type: 'nested',
        es_include_in_parent: true}
});

storeSchema.plugin(mongoosastic, {
    esClient: esclient
});
articleSchema.plugin(mongoosastic, {
    esClient: esclient
});
global.DBModel.Artikel = global.mongoose.model('Artikel', articleSchema);

global.DBModel.Store = global.mongoose.model('Store', storeSchema);

当我现在从路线开始搜索" /搜索"它有这个示例代码:

global.DBModel.Artikel.search({
                    query_string: {
                        query: "*"
                    }
                }, {
                    hydrate: true
                }, function (err, results) {
                    if (err)
                        return res.send(500, {error: err});
                    res.send(results);
                }); 

我得到了这个结果:

...
      {
        "_id": "56ab6b15352a43725a21bc92",
        "stores": [
          "56ab6b03352a43725a21bc91"
        ],
        "Name": "daaadd",
        "ArtikelNummer": "232",
        "__v": 0,
        "_stores": []
      }
    ]
  }
}

我如何直接获得一个对象而不是id" 56ab6b03352a43725a21bc91"?

1 个答案:

答案 0 :(得分:0)

我必须为插件选项显式添加populate选项,以便为填充的嵌套文档编制索引。在你的情况下定义像这样的mongoosastic插件可能有效:

storeSchema.plugin(mongoosastic, {
    esClient: esclient,
    populate: [
        { path: '_articles', select: '_id Name Kategorie' }
    ]
});
articleSchema.plugin(mongoosastic, {
    esClient: esclient,
    populate: [
        { path: '_stores', select: '_id Name Email' }
    ]
});

此外,您还应在内部字段选项中指定es_schema,如下所示:

var articleSchema = new Schema({       
    Name: {type: String, es_indexed: true},
    Kategorie: String,
    ....
    _stores: {type: [storeSchema],
        es_indexed: true,
        es_type: 'nested',
        es_include_in_parent: true,
        es_schema: storeSchema
   }
});

请参阅此处的示例:https://github.com/mongoosastic/mongoosastic#indexing-mongoose-references