我如何做mongoosastic填充?
我的目标是填写某些领域的mongoosasticsearch,但如果我做下面的代码,它将永远返回
这是代码
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中填充某个类别?
您正在使用
populate: [ {path: 'categories', select: 'name'} ]
但是你的代码中的categories
是undefined
。
您必须在类别中使用类别,因为您已经在模式声明中提到了键作为类别
希望它能解决你的问题。
编辑:
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