【问题标题】:Issue while fetching mongo data with "Ref" in Mongoose在 Mongoose 中使用“Ref”获取 mongo 数据时出现问题
【发布时间】:2019-12-31 00:29:50
【问题描述】:

嘿,我一直在尝试 graphql,所以有一种情况我被困在“Ref”部分......假设我有太多如下定义的模式

用户.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"
            }
          ]
        }
      }
    ]
  }
}

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

【问题讨论】:

    标签: javascript node.js mongodb mongoose graphql


    【解决方案1】:

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

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 2011-11-20
    • 2020-01-30
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多