问题
I am trying to build a many to many relationship schema and trying to build a virtual to access the same. Finally trying to get the embedded objects when queried. My schema looks something like below
//Mongoose Schema
var item1 = new Schema ({
_id: Number,
Item2Id: [{type: Number, ref: item2}],
Detail1: String,
Detail2: String
...
},{toObject:{virtuals:true},toJSON:{virtuals:true}});
var item2 = new Schema ({
_id: Number,
Item1Id: [{type: Number, ref: item1}],
Detail1: String,
Detail2: String
...
},{toObject:{virtuals:true},toJSON:{virtuals:true}});
item1.virtual('Item2Details').get(function() {
var ids = this.Item2Id;
details = [];
ids.forEach(function(id, idx, array) {
item2.findOne({'_id': id}).exec(function (err, doc) {
details.push(doc);
if(idx === array.length - 1)
return details;
});
});
});
//app.js
app.get('/item1/:id', function(req, res){
item1.findOne({'_id':req.params.id}).exec(function(err, doc){
res.send(doc);
});
});
My expectation was if item1 was
{
_id:1,
Item2Id: [2, 3],
Detail1: 'abc',
Detail2: 'xyz'
}
and item2 were
{
_id:2,
Item2Id: [1],
Detail1: 'abc',
Detail2: 'xyz'
}
{
_id:3,
Item2Id: [1],
Detail1: 'abc',
Detail2: 'xyz'
}
resulting response should be
{
_id:1,
Item2Id: [2,3],
Item2Details: [
{_id:2,
Item2Id: [1],
Detail1: 'abc',
Detail2: 'xyz'},
{_id:3,
Item2Id: [1],
Detail1: 'abc',
Detail2: 'xyz'}],
Detail1: 'abc',
Detail2: 'xyz'
}
However, I am unable to get the same. I tried, using res.send(doc.Item2Details) and no luck. Have also tried using populate in find query, it too fails with some local and foreign error. Assume it is referring to have virtuals defined in different way (http://mongoosejs.com/docs/populate.html), even when I tried it with following link it didn't work.
ref: 'item2',
localField: '_id',
foreignField: 'Item2Id'
Appreciate any pointer in right direction.
回答1:
You set {toObject: true}
but you missed using it:
res.send(doc.toObject());
来源:https://stackoverflow.com/questions/41123708/how-to-access-mongoose-virtuals-in-express