22

My goal is to populate certain fields in mongoosastic search, but if I do the following codes, it will always return

enter image description here

Here's the code

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

What should I do to populate a certain category in mongoosastic?

Vini.g.fer
  • 11,639
  • 16
  • 61
  • 90
Jack Moscovi
  • 2,195
  • 7
  • 30
  • 49
  • Did you get this to work? I have a similar issue where I get 0 hits when populating. I've read over the docs numerous time, but I'm not sure where I went wrong. If you could provide insight: http://stackoverflow.com/questions/37758652/mongoosastic-elastic-search-will-not-return-any-hits-when-populating – someoneHere Jun 11 '16 at 00:07
  • are you solve this problem? – Mikhail Nov 01 '16 at 09:51

2 Answers2

0

You are using

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

But categories in your code is undefined.

You have to use category in the place of categories as you have mentioned the key as category in the schema declaration

Hope it will solve your problem.

Akhil P
  • 1,580
  • 2
  • 20
  • 29
-1

Edit:

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

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

And use populate: .populate('_category ', 'name')

Hope it will help you.

See more: http://mongoosejs.com/docs/populate.html

JON
  • 965
  • 2
  • 10
  • 28
Alex
  • 3,646
  • 1
  • 28
  • 25