【问题标题】:Query status of inner array of in MongoDB using mongoose使用mongoose查询MongoDB内部数组的状态
【发布时间】:2020-11-10 15:49:12
【问题描述】:

我有一个用户模式,其关注者数组如下所示,

const userSchema = new mongoose.Schema({
  firstname: {
    type: String,
    required: true,
  },
  lastname: {
    type: String,
    required: true,
  },
  followers: [{ type: ObjectId, ref: "User" }],
  following: [{ type: ObjectId, ref: "User" }],
});

当我查询用户列表时,我需要两个额外字段 isFollowing 和 isFollower (isFollowing存在于我的followers数组中,isFollower存在于followers数组中)

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    看起来你需要populate followersfollowing 数组:

    const users = await User.findOne({ ... })
                             .populate('followers')
                             .populate('following');
    

    【讨论】:

      猜你喜欢
      • 2022-08-19
      • 1970-01-01
      • 2014-05-13
      • 2011-10-07
      • 2014-10-10
      • 2021-06-29
      • 2015-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多