我在查询时关注了如何使用populate
的凌乱的Mongoose文档,但我的virtual
没有显示任何内容。
以下是我的模特:
客户模型:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var CustomerModel = new Schema({
name: {
type: String,
required: true
},
payment: {
id: {
type: String,
required: true
}
},
{
// ...
}
});
module.exports = CustomerModel;
帐户模型:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var AccountSchema = new Schema({
customer: {
type: String,
required: true
}, {
// ...
}
}, {
toJson: {
virtuals: true
}
});
AccountSchema.virtual('customer_id', {
ref: 'Customer',
foreignField: 'payment.id',
localField: 'customer',
justOne: true
});
module.exports = AccountSchema;
这里的问题是,当我使用与find
链接的populate
以及帐户架构中定义的路径customer_id
时,我不会检索客户的信息。
这是我正在进行的查询:
Account.findOne({'customer': 'his_id'}).populate('customer_id').exec(function(err, results) {
// I am just retrieving the 'his_id', so it has not been populated.
});
知道我怎么能在一个查询中做到这一点? (顺便说一下,选择我想从Customer模型中检索的字段)。
调试为我提供了该查询的以下信息:
Mongoose: accounts.find({ customer: 'his_id' }, { fields: {} })
Mongoose: customers.find({ 'payment.id': { '$in': [ 'his_id' ] } }, { fields: {} })