繁体   English   中英

在猫鼬中使用“ Ref”获取mongo数据时出现问题

[英]Issue while fetching mongo data with “Ref” in Mongoose

嘿,我一直在尝试graphql,所以有一种情况我卡在“ Ref”部分中……假设我也有如下定义的模式

user.js的

const userschema = new Schema({
  email: {
    type: String,
    required: true
  },
  createdevents: [
    {
      type: Schema.Types.ObjectId,
      ref: "Event"
    }
  ]
});
module.exports = mongoose.model("User", userschema);

然后是events.js

const eventschema=new Schema({
    title:{
        type:String,
        required:true
    },
    price:{
        type:Number,
        required:true
    },
    creator:{
        type:Schema.Types.ObjectId,
        ref:'User'
    }
})
module.exports=mongoose.model('Event',eventschema)

因此,当我使用事件数据时,我尝试通过以下populate()方法获取用户属性

events: () => {
        return Event.find().populate('creator').then(result => {
          return result.map(e => {
            return { ...e._doc, _id: e._doc._id.toString() };
          });
        });
      }

所以我现在可以访问所有用户属性,但是如果我需要访问User.js中“ createdevents”内部的事件字段怎么办,这意味着我需要再次运行填充方法,以便可以将所有事件属性存储在内部“ createdevents”,但下面带有相同的代码

简而言之,无论如何,我需要在这里应用另一种填充方法

 events: () => {
                return Event.find().populate('creator').then(result => {
                  return result.map(e => {
                    return { ...e._doc, _id: e._doc._id.toString() };
                  });
                });
              }

这样我就可以在createdevents中的所有事件属性中再花一个时间

我需要的订单就像

事件(创建者)->已使用填充(已实现所有用户属性)->现在在User.js中,我必须再次应用填充以实现所有事件属性

抱歉,这听起来很奇怪,我无法解释,我认为这有点像多种族人口

现在,如果我运行查询

query{
  events{
    title
    creator{
      _id
      email
      createdevents{
        _id
      }
    }
  }
}

我得到

{
  "data": {
    "events": [
      {
        "title": "asd",
        "creator": {
          "_id": "5d64354bfd7bb826a9331948",
          "email": "test@test.com",
          "createdevents": [
            {
              "_id": "5d6435a78150062703df70ff"
            },
            {
              "_id": "5d6435ab8150062703df7101"
            },
            {
              "_id": "5d6435cc8150062703df7102"
            }
          ]
        }
      }
    ]
  }
}

很好,但是我只能获取事件的_id,我需要获取可以通过填充方法实现的所有属性

您可以通过以下方式跨多个级别进行填充:

Event.find()
     .populate({
       path: 'creator',
       populate: { path: 'createdevents' }
     });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM