【问题标题】:Mongoose - Populate not filtering correctlyMongoose - 填充未正确过滤
【发布时间】:2017-02-12 00:32:06
【问题描述】:

我只想返回状态为“活动”的数组中的朋友对象。然而,当我发出获取请求时,我仍然看到状态为“待定”的朋友。

这是我的索引控制器:

index: function(req, res) {
    User.findOne({
      _id: req.params.id
    })
    .populate({path: "roommates", match: {status: {$eq: "active"}}})
    .exec(function(err, user) {
      console.log(user.roommates);
    })
  }

这是记录到控制台的结果:

[ { _id: 57f2e5e02d58f51a8284bc11,
    balance: 0,
    requests: [],
    status: 'pending' } ]

这是我的用户模型供参考:

var UserSchema = new Schema({
  name: String,
  username: {
    type: String,
    required: [true, "Please enter a username"],
    minlength: [6, "Username must be at least 6 characters"],
    maxlength: [15, "Username cannot exceed 15 characters"],
    unique: true
  },
  password: {
    type: String,
    required: [true, "Please enter a password"],
    minlength: [6, "Password must be at least 6 characters"],
    maxlength: [17, "Password cannot exceed 17 characters"],
  },
  roommates: [{roommate: {type: Schema.Types.ObjectId, ref: "User", unique: true}, status: {type: String, default: "pending"}, requests: [{type: Schema.Types.ObjectId, ref: "Request"}], balance: {type: Number, default: 0}}]
})

我只想返回状态为“活跃”的朋友。有什么帮助吗? 谢谢!

【问题讨论】:

  • “用户”模式在哪里,或者它在室友中引用自我模式??
  • 我不清楚你在问什么?用户模式在哪里?它在底部代码块的上方。

标签: node.js mongodb express mongoose mongoose-populate


【解决方案1】:

由于用户架构中的参考是室友,所以人口应该是:

    .populate({path: "roommates.roommate"})

结果应该是这样的:

[ { roommate: [Object], //populated object
    balance: 0,
    requests: [],
    status: 'pending' } ]

现在,即使你这样做:

.populate({path: "roommates.roommate", match: {status: {$eq: "active"}}})

它应该返回 null:

[ { roommate: null,
balance: 0,
requests: [],
status: 'pending' } ]

因为您在室友中填充用户并且用户架构没有状态或余额字段。状态和余额是室友数组内室友对象中的附加字段。

当字段是引用对象的架构的一部分时,匹配有效。

一种选择是从室友中删除状态和余额字段,并使其成为用户架构的一部分。

但是,使用相同的设计,您可以使用过滤,因为室友的长度几乎不会超过 10,这将是非常小的处理。

    User.findOne({
    _id: req.params.id
     })
    .exec(function(err, user) {
        user.roommates = user.roommates.filter(function (rm) {
            return rm.status == "active"
        });
        console.log(user.roommates)
    })

【讨论】:

  • 谢谢,但是这不起作用,因为状态表示某种室友关系的状态。例如,一个用户将有许多状态,该用户的每个相应室友都有一个状态。因此,将状态作为属性是行不通的。我不得不过滤前端角度的数据,效果很好。
  • 在您的情况下,另一个集合“室友”将是合适的。它将具有状态和成员字段。 members 将是一个包含两个用户 id 的数组,因此它将处理来自两端的多对多关系。用户 A 和 B 将拥有一份带有状态的室友文档。
猜你喜欢
  • 2018-12-28
  • 2016-07-11
  • 1970-01-01
  • 2021-12-17
  • 2020-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多