首页 > 解决方案 > 如何从猫鼬中的引用模型中获取字段?

问题描述

嘿,伙计们需要一些查询帮助,以下是模型,我将其引用到另一个名为 Project 的模型

const User= new mongoose.Schema({
  featured_projects: {
    type: [
      {
        type: Schema.Types.ObjectId,
        ref: 'Project'
      }
    ],
  }
}, {
    timestamps: true,
  });

//下面输出

{
    "featured_projects" : ["5bd54c7d65194f200d1c6e2d","5bd41b953fc9f040b08995df"]
}

项目模型存储为

{
                "en": {
                    "isActive": true,
                    "amneties": [],
                    "carasouel_images": [],
                    "location": "location (en)",
                    "name": "name (en)"
                },
                "th": {
                    "isActive": true,
                    "amneties": [],
                    "carasouel_images": [],
                    "location": "location (th)",
                    "name": "name (th)"
                },
                "_id": "5bd54c7d65194f200d1c6e2d",
                "createdAt": "2018-10-28T05:43:25.982Z",
                "updatedAt": "2018-10-28T05:43:25.982Z",
                "__v": 0
            },

我试图从查询中获取“en”

this.find(options)
      .populate({
        path: 'featured_projects',
        populate:'en'
      })
      .sort({ createdAt: - 1 })
      .skip(perPage * (page - 1))
      .limit(perPage)
      .exec();

但是不起作用,非常感谢任何帮助,或者非常感谢任何建议。

但是,如果我直接尝试从项目中获取“en”字段,我会这样做并且正在工作

this.find(options)
      .select({ [lang]: 1 })
      .sort({ createdAt: -1 })
      .skip(perPage * (page - 1))
      .limit(perPage)
      .exec();

先感谢您 !:)

标签: mongodbmongoosemongodb4.0

解决方案


推荐阅读