如何在Express中访问猫鼬虚拟机 [英] How to access mongoose virtuals in express

查看:77
本文介绍了如何在Express中访问猫鼬虚拟机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试建立多对多关系架构,并试图建立一个虚拟的访问架构.最后尝试在查询时获取嵌入的对象.我的架构如下图所示

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);
  });
});

我的期望是如果item1是

My expectation was if item1 was

{
  _id:1,
  Item2Id: [2, 3],
  Detail1: 'abc',
  Detail2: 'xyz'
}

和item2是

{
  _id:2,
  Item2Id: [1],
  Detail1: 'abc',
  Detail2: 'xyz'
}
{
  _id:3,
  Item2Id: [1],
  Detail1: 'abc',
  Detail2: 'xyz'
}

结果应为

{
  _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'
}

但是,我无法获得相同的结果.我尝试使用res.send(doc.Item2Details),但没有运气.还尝试在查找查询中使用填充,它也因某些本地和外部错误而失败.假设它是指以不同的方式定义虚拟对象( http://mongoosejs.com/docs/populate. html ),即使我尝试通过以下链接进行操作也无法正常工作.

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.

推荐答案

您设置了{toObject: true},但错过了使用它:

You set {toObject: true} but you missed using it:

res.send(doc.toObject());

这篇关于如何在Express中访问猫鼬虚拟机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆