我在尝试让mongoose中的populate功能工作时遇到了最大的麻烦。我已经查看了SO上的所有主题,没有任何帮助。我的架构在下面列出。
'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);
我在Mongoose Repl中尝试了以下所有查询,但没有任何作用
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()

有没有人有任何建议?这是杀了我!!
答案 0 :(得分:1)
好奇!
下面的初始化,是否必须在ProductSchema中引用之前完成?
mongoose.model('Feature', feature);
mongoose.model('Extra', extra);
像这样的东西
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'
}
});
这应该可行
models.Product.find().populate("extras")