【问题标题】:How do I do populate on mongoosastic?我如何填充 mongoosastic?
【发布时间】:2016-05-13 00:09:42
【问题描述】:

我的目标是填充 mongoosastic 搜索中的某些字段,但如果我执行以下代码,它总是会返回

这是代码

var mongoose = require('mongoose');
var Category = require('./category');
var mongoosastic = require('mongoosastic');
var Schema = mongoose.Schema;

var ProductSchema = new Schema({
  category: { type: Schema.Types.ObjectId, ref: 'Category', es_schema: Category, es_indexed:true, es_select: 'name'},
  name: String,
  price: Number,
  image: String
});

ProductSchema.plugin(mongoosastic, {
  hosts: [
    'localhost:9200'
  ],
  populate: [
    {path: 'category', select: 'name'}
  ]
});

module.exports = mongoose.model('Product', ProductSchema);


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

var CategorySchema = new Schema({
  name: { type: String, unique: true, lowercase: true}
});

module.exports = mongoose.model('Category', CategorySchema);

api.js

router.post('/search', function(req, res, next) {
  console.log(req.body.search_term);
  Product.search({
    query_string: { query: req.body.search_term }
  }, function(err, results) {
    if (err) return next(err);
    res.json(results);
  });
});

我应该怎么做才能填充 mongoosastic 中的某个类别?

【问题讨论】:

  • 你让它工作了吗?我有一个类似的问题,我在填充时获得 0 次点击。我已经多次阅读文档,但我不确定我哪里出错了。如果您能提供见解:stackoverflow.com/questions/37758652/…
  • 这个问题你解决了吗?

标签: node.js elasticsearch mongoose mongoosastic


【解决方案1】:

你正在使用

populate: [
  {path: 'categories', select: 'name'}
]

但是您代码中的categoriesundefined

你必须像你一样使用 category 来代替 categories 在模式声明中提到键作为类别

希望它能解决你的问题。

【讨论】:

    【解决方案2】:

    编辑:

    category: { type: Schema.Types.ObjectId, ref: 'Category', es_schema: Category, es_indexed:true, es_select: 'name'},
    

    => _category : { type: Schema.Types.ObjectId, ref: 'Category' },

    并使用填充:.populate('_category ', 'name')

    希望对你有所帮助。

    查看更多:http://mongoosejs.com/docs/populate.html

    【讨论】:

    • 这只适用于猫鼬,我说的是猫鼬。
    猜你喜欢
    • 2017-07-06
    • 2016-10-12
    • 2013-03-19
    • 1970-01-01
    • 2019-08-08
    • 2011-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多