【问题标题】:How I can select only one field from every object in array using Mongoose?如何使用 Mongoose 从数组中的每个对象中仅选择一个字段?
【发布时间】:2017-04-16 18:48:40
【问题描述】:

我有架构:

{
  name: String,
  surname: String,
  note: String,
  someField: String,
  secondSomeField: String
  blackList: [{
     userId: mongoose.Types.ObjectId,
     reason: String
  }]
}

我需要选择包含所有字段的文档,但在黑名单字段中我只需要选择 userId。例如我想要的:

{
      name: "John",
      surname: "Doe",
      note: "bwrewer",
      someField: "saddsa",
      secondSomeField: "sadsd",
      blackList: [58176fb7ff8d6518baf0c931, 58176fb7ff8d6518baf0c932, 58176fb7ff8d6518baf0c933, 58176fb7ff8d6518baf0c934]
}

我该怎么做?当我这样做时

Schema.find({_id: myCustomUserId}, function(err, user) {
      //{blackList: [{userId: value}, {userId: value}]}
      //but i need
      //{blackList: [value, value, value]}
})

【问题讨论】:

  • 答案是:Schema.aggregate( {$match: {_id: mongoose.Types.ObjectId(myCustomId)} }, {$project: {blackList: "$blackList.userId", name: true, surname: true, someField: true}} ).exec(fn)

标签: node.js mongodb mongoose


【解决方案1】:

如果要默认隐藏该字段:

{
  name: String,
  surname: String,
  note: String,
  someField: String,
  secondSomeField: String
  blackList: [{
     userId: mongoose.Types.ObjectId,
     reason: {type:String, select:false}
  }]
}

如果您只是想在该查询中排除:

Schema
    .find({_id: myCustomUserId})
    .select("-blackList.reason")
    .exec(function (err, user) {
      //your filtered results
})

未经测试,但它们应该都可以工作。

【讨论】:

  • 我没有测试,但我测试了一个类似的查询,结果是:blackList: [{userId: id}, {userId: id}] 但我需要:[id, id, id],因为我将执行下一个查询:Schema.find({_id: {$nin: arrayOfIds}})
  • 您可以通过这种方式保留第一个查询并使用$elemMatch 编辑下一个查询。看到这个答案stackoverflow.com/questions/14040562/…
  • elemMatch - 在数组中搜索,对我没有帮助。我需要不在我的黑名单中的搜索用户
  • 我尝试查询 alfredopacino,它不起作用(结果是:blackList: [{userId: id}, {userId: id}] ((
【解决方案2】:
Schema.aggregate( {$match: {_id: mongoose.Types.ObjectId(myCustomId)} }, {$project: {blackList: "$blackList.userId", name: true, surname: true, someField: true}} ).exec(fn)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-27
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多