我目前正在使用mongoose v4.10.8
并尝试在定义的模型上填充多个数组。
TransportModel.js
//Transport model
'use strict';
const mongoose = require('mongoose');
const TransportSchema = new mongoose.Schema({
tag: {
type: String,
enum: ['X', 'Y'],
required: true,
unique: true
},
chairs: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Chair"
}],
targets: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Target"
}]
});
module.exports = mongoose.model('Transport', TransportSchema);
ChairModel.js
//Chair model
'use strict';
const mongoose = require('mongoose');
const ChairSchema = new mongoose.Schema({
product_name: {
type: String,
required: true,
unique: true
},
description: {
type: String,
unique: false,
required: false
}
});
module.exports = mongoose.model('Chair', ChairSchema);
TargetModel.js
//Target model
'use strict';
const mongoose = require('mongoose');
const TargetSchema = new mongoose.Schema({
target_name: {
type: String,
required: true,
unique: true
},
location: {
type: String,
required: true,
unique: false
},
description: {
type: String,
unique: false,
required: false
}
});
module.exports = mongoose.model('Target', TargetSchema);
完成上述配置后,我创建了一个Chair
文档和一个Target
文档。
之后,我在路由上调用以下逻辑来获取单个Transport
文档:
TransportModel.findOne({
tag: 'X'
})
.populate("chairs")
.populate("targets")
.exec(function(err, transport) {
if (err) {
console.error(err);
}
console.log('Transport: ', transport);
});
});
以下是检索到的文件:
{
"_id": "xxxx9999xxxx9999xxxx9999",
"tag": "X",
"__v": 1,
"chairs": [],
"targets": []
}
因此,即使我查询了Chairs
和Targets
个集合,并且我确实至少有一个文档,但Transport
文档仍未填充。
此外,我还尝试了.populate()
的增强版本,但我不断获得空数组:
.populate({
path: "chairs",
model: "Chair"
})
.populate({
path: "targets",
model: "Target"
})
答案 0 :(得分:-1)
如果您已经将新的椅子和目标推入了传输模型,您可以使用 mongoose-deep-populate 模块更好地填充它,这是一个如何配置设置的简单示例
var mongoose = require('mongoose');
var deepPopulate = require('mongoose-deep-populate')(mongoose);
var Schema = mongoose.Schema;
var kindsSchema = new Schema({
name:{type:String,required:true,unique:true},
components:[{type:Schema.ObjectId,ref:'components'}],
associatedView:{type:String,default:'home/fragances'},
discount:{type:Number,default:0},
description:{type:String,default:'Nueva categoria'},
created_at:{type:Date,default:Date.now},
modified_at:{type:Date,required:true}
});
kindsSchema.plugin(deepPopulate,{
whitelist:[
'components.attributes',
]
populate:{
'components':{
select['attributes','discount']
}
}
});