【发布时间】:2019-02-10 16:40:02
【问题描述】:
我正在尝试在 mongoose 中创建一个虚拟填充器,但我在这方面遇到了困难,我不知道这是一个限制、错误还是我做错了什么。
这个想法是一个用户可以是多个组的成员,然后我可以通过查询在组数组中具有其 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 函数来执行此操作,但我想知道是否可以使用虚拟机来执行此操作,或者我在浪费时间。
【问题讨论】:
标签: mongoose mongoose-schema mongoose-populate