【问题标题】:Mongoose, populate where an ID is specific to a project referenceMongoose,填充 ID 特定于项目引用的位置
【发布时间】:2017-04-10 11:07:27
【问题描述】:

我正在尝试填充一个猫鼬模型,我只希望返回的项目是与 ID 匹配的项目。

编辑更新:在下面的用户模型中,我需要首先通过 id 找到正确的用户,然后对于 task 属性,我需要在 projectID 匹配 req.params.ID 的位置填充它。我怎样才能只填充projectIDreq.params.ID 匹配的任务。我已经包含了我的完整用户模型以及任务模型

//用户架构

var UserSchema = new Schema({
  name: {
    type: String,
    trim: true,
    required: "First Name is Required"
  },
  username: {
    type: String,
    trim: true,
    required: "Username is Required"
  },
  skills: {
    type: String,
    trim : true
  },
  avatar: {
    type: String
  },
  SQLid: {
    type: Number
  },
  userCreated: {
    type: Date,
    default: Date.now
  },
  lastUpdated: { 
    type: Date
  },
  adminTeams: [{
    type: Schema.Types.ObjectId,
    ref: "Team"
  }],
  team: [{
    type: Schema.Types.ObjectId,
    ref: "Team"
  }],
  task: [{
    projectID: {
      type: String
    },
    theTask: {
      type: Schema.Types.ObjectId,
      ref: "Task" 
    }
  }]
});

//任务架构

var TodoSchema = new Schema({
  task: {
    type: String
  }
});

我如何才能仅在 projectID 等于特定 ID 的情况下填充 task。我试过了

User.findById({ "_id": req.params.id }).populate({ path: 'task', match: {projectID: req.params.pID}, select: 'theTask' })
  .exec(function(err, docs){
    console.log("POPULATE TASKS DOCS", docs)

但这表明文档是空的。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您可以使用$elemMatch,它会为您提供与您的 projectId 匹配的所有文档并填充您的任务文档。 所以查询将是 -

    var query={
               task:{
                         $elemMatch:{
                                projectId: req.params.id
                                     }  
                        }
               }
    
    User.find(query)
    .populate('theTask')
    .select('theTask')  // use for getting selective data from document
    .exec(function(){}) //your callback fuction
    

    希望我能回答你的问题。

    谢谢。

    【讨论】:

    • 我试过了,但它返回的是任务和项目的 _id 而不是实际任务。我已经包含了我的完整用户模型和任务模型
    【解决方案2】:

    在您的任务 schma 中,您将任务类型的类型保留为 string 并且在您的用户模式中 theTask 具有任务的引用,并且其 Self 的任务只是 string 。这就是为什么它没有被填充..

    因此将任务架构更改为(保持简单)-

    var Task= new Schema({
      name :string
         });
    

    填充需要参考 ID 以获取整个文档

    【讨论】:

      猜你喜欢
      • 2022-06-14
      • 2013-03-23
      • 1970-01-01
      • 1970-01-01
      • 2015-04-08
      • 2018-05-21
      • 2017-03-22
      • 2016-01-07
      • 1970-01-01
      相关资源
      最近更新 更多