我正在尝试用mongoose创建一个虚拟的populator,但我对这方面感到困惑,我不知道这是一个限制,一个bug,还是我做错了什么。
想法是用户可以是多个组的成员,然后我可以通过查询在groups数组上具有其id的用户来填充组模式中的虚拟。
我创建了一个示例(基于原始的mongoose文档)。
卢卡·特里利(Luca Turilli)已经进入了许多乐队,有时同时也是如此,因此原始模型(其中乐队是单个乐队)不会削减意大利的电力金属。
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('connected to db');
});
var artistSchema = new Schema ({
name: String,
bands: [{type: String, ref: 'band'}]
});
var bandSchema = new Schema ({
name: String
},{
toJson:{virtuals:true},
toObject: {virtuals:true}
});
bandSchema.virtual('lineup', {
ref: 'Artist',
localField: 'name',
foreignField: 'bands'
});
var Artist = mongoose.model('Artist', artistSchema);
var Band = mongoose.model('Band', bandSchema);
/* Comment this if you already populated the database */
Band.create({name:'Dreamquest'});
Band.create({name:'Luca Turilli'});
Band.create({name:'Rhapsody of Fire'});
Artist.create({name:'Luca Turilli', bands:['Dreamquest','Luca Turilli','Rhapsody of Fire']});
Artist.create({name:'Olaf Hayer', bands:['Luca Turilli']});
Artist.create({name:'Sascha Paeth', bands:['Luca Turilli','Dreamquest']});
Artist.create({name:'Robert Hunecke-Rizzo', bands:['Luca Turilli', 'Dreamquest']});
Artist.create({name:'Dominique Leurquin', bands:['Dreamquest', 'Rhapsody of Fire']});
Artist.create({name:'Patrice Guers', bands:['Rhapsody of Fire']});
Artist.create({name:'Alex Landenburg', bands:['Rhapsody of Fire']});
/*stop commenting here*/
Band.find(function(err, bands) {
if (err) return console.error(err);
console.log(bands);
});
预期的产出将是:
[ { _id: 5b8fd9eef72e14315b52985f,
name: 'Dreamquest',
__v: 0,
lineup: [Artist entries of Luca,Sascha,Robert and Dominique]},
.... more bands
]
相反,我明白了
[ { _id: 5b8fd9eef72e14315b52985f,
name: 'Dreamquest',
__v: 0,
lineup: null,
id: '5b8fd9eef72e14315b52985f' },
{ _id: 5b8fd9eef72e14315b529860,
name: 'Luca Turilli',
__v: 0,
lineup: null,
id: '5b8fd9eef72e14315b529860' },
{ _id: 5b8fd9eef72e14315b529861,
name: 'Rhapsody of Fire',
__v: 0,
lineup: null,
id: '5b8fd9eef72e14315b529861' } ]
我试图在相同的情况下搜索示例或人,但我没有找到太多信息。我知道我可能会得到一个getter函数来执行此操作,但我想知道是否可以使用虚拟文件或我浪费时间。
最后,响应很简单:virtuals:true
does不会自动填充字段,并且虚拟不会自行填充。这令人困惑,因为看起来填充的虚拟意味着虚拟自身填充......
无论如何,正确的查询是:
Band.find({}).populate('lineup').exec(function(err,bands) {
if (err) return console.error(err);
console.log(bands);
}
与任何手动人群一样,如果您计划定期访问此信息,您可以将“查找”,“查找”和“保存”(以及其他)设置为自动填充。