Mongoose:在一个查询中使用virtuals进行填充

Mongoose:在一个查询中使用virtuals进行填充,mongoose,populate,Mongoose,Populate,我在查询时遵循了关于如何使用填充的混乱的Mongoose文档,但是我的虚拟中没有显示任何内容 以下是我的模型: 客户模式: var mongoose=require('mongoose'); var Schema=mongoose.Schema; var CustomerModel=新架构({ 姓名:{ 类型:字符串, 必填项:true }, 付款:{ 身份证:{ 类型:字符串, 必填项:true } }, { // ... } }); module.exports=CustomerModel;

我在查询时遵循了关于如何使用
填充
的混乱的Mongoose文档,但是我的
虚拟
中没有显示任何内容

以下是我的模型:

客户模式:

var mongoose=require('mongoose');
var Schema=mongoose.Schema;
var CustomerModel=新架构({
姓名:{
类型:字符串,
必填项:true
},
付款:{
身份证:{
类型:字符串,
必填项:true
}
},
{
// ...
}
});
module.exports=CustomerModel;
账户模式:

var mongoose=require('mongoose');
var Schema=mongoose.Schema;
var AccountSchema=新架构({
客户:{
类型:字符串,
必填项:true
}, {
// ...
}
}, {
toJson:{
虚拟的:真的
}
});
AccountSchema.virtual('customer\u id'{
参考:“客户”,
foreignField:“payment.id”,
localField:'客户',
真的吗
});
module.exports=AccountSchema;
这里的问题是,当我使用
find
链接到
populate
以及帐户架构中定义的路径
customer\u id
时,我没有检索客户的信息

以下是我正在做的查询:

Account.findOne({'customer':'his_id')).populate('customer_id').exec(函数(err,results){
//我正在检索“他的id”,因此它尚未填充。
});
你知道我如何在一个查询中完成吗?(顺便说一句,选择我想从客户模型中检索的字段)

调试将为该查询提供以下信息:

Mongoose: accounts.find({ customer: 'his_id' }, { fields: {} })
Mongoose: customers.find({ 'payment.id': { '$in': [ 'his_id' ] } }, { fields: {} })

也许
mongoose.set('debug',true)
可以给你一些指示。在回调中执行
console.log(err,results)
时会发生什么?不过,随机的问题是,为什么不让AccountSchema
customer
a成为客户呢?@Mikey,我刚刚在帖子中添加了调试输出。回调的结果仅为Account文档,仅此而已(没有虚拟文档)。关于引用,我可以在没有_id的情况下进行引用吗?(我希望它是payment.id)。关于我的上一条语句,为什么不直接执行
customer:{type:Schema.Types.ObjectId,ref:'customer',required:true}
?然后您应该能够执行
Account.findOne({'customer':'his_id')).populate('customer').exec(函数(err,Account){…})
。您可以通过执行
account.customer.\u id
或其他操作来检索客户信息。这就是为什么我指定我不想使用
\u id
,而是
payment.id
。我可以用
ref
来做吗?你说得对。但是,我如何指定需要它匹配的字段(
customer
从帐户模型匹配
payment.id
从客户模型)?如何指定要输出的字段?(例如,我不想输出
password
字段)。谢谢也许
mongoose.set('debug',true)
可以给你一些指示。在回调中执行
console.log(err,results)
时会发生什么?不过,随机的问题是,为什么不让AccountSchema
customer
a成为客户呢?@Mikey,我刚刚在帖子中添加了调试输出。回调的结果仅为Account文档,仅此而已(没有虚拟文档)。关于引用,我可以在没有_id的情况下进行引用吗?(我希望它是payment.id)。关于我的上一条语句,为什么不直接执行
customer:{type:Schema.Types.ObjectId,ref:'customer',required:true}
?然后您应该能够执行
Account.findOne({'customer':'his_id')).populate('customer').exec(函数(err,Account){…})
。您可以通过执行
account.customer.\u id
或其他操作来检索客户信息。这就是为什么我指定我不想使用
\u id
,而是
payment.id
。我可以用
ref
来做吗?你说得对。但是,我如何指定需要它匹配的字段(
customer
从帐户模型匹配
payment.id
从客户模型)?如何指定要输出的字段?(例如,我不想输出
password
字段)。谢谢