Reputation: 1295
I am having the most awful trouble trying to get the populate feature in mongoose to work. I have looked at all the threads here on SO and nothing has helped. My schema is mapped out below.
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Prodcut Feature Extra
*/
var extra = new Schema({
name: {
type: String,
default: '',
required: 'Please fill Product name',
trim: true
},
price: {
type: Number,
default: 0
},
description: {
type: String,
trim: true
},
toolTip: {
type: String,
trim: true,
min: 3,
max: 140
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
/**
* Product Feature Schema
*/
var feature = new Schema({
name: {
type: String,
default: '',
required: 'Please fill feature name',
trim: true
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
/**
* Product Schema
*/
var ProductSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill Product name',
trim: true
},
created: {
type: Date,
default: Date.now
},
features: [feature],
extras: [extra],
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Feature', feature);
mongoose.model('Extra', extra);
mongoose.model('Product', ProductSchema);
I have tried all of the following queries in a Mongoose Repl but nothing works
models.Product.find().populate("Extra", "name").exec()
models.Product.find().populate({path: "extras", location: "Extra"}).exec()
models.Product.find().populate('extras', 'name').exec()
models.Product.find().populate('extras', 'Extra').exec()
Does anyone have any suggestions? This is killing me!!
Upvotes: 0
Views: 377
Reputation: 662
Just curious!
This initialization below, isn't has to be done before referencing in ProductSchema?
mongoose.model('Feature', feature);
mongoose.model('Extra', extra);
Something like this
mongoose.model('Feature', feature);
mongoose.model('Extra', extra);
var ProductSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill Product name',
trim: true
},
created: {
type: Date,
default: Date.now
},
features: [ {
type: Schema.ObjectId,
ref: 'Feature'
}],
extras: [ {
type: Schema.ObjectId,
ref: 'Extra'
}],
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
Than this should work
models.Product.find().populate("extras")
Upvotes: 0