【问题标题】:Retrieve information from reference ObjectId MongoDB从参考 ObjectId MongoDB 中检索信息
【发布时间】:2021-08-19 19:42:50
【问题描述】:

我有这个方案

const friendSchema = new mongoose.Schema(
  {
    friend_id: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Users",
  },
     status: String,
  },
  { _id: 0 } 
);

这个模型正在使用它

const UserSchema = new mongoose.Schema({
  name: {
    type: String,
  },
  password: {
    type: String,
  },
  rate: {
    type: Number,
    default: 0,
  },
  friend: [friendSchema],
})

就像用户有朋友一样 我想让每个用户和他们的朋友(姓名 - 率)

status在friendSchema中是好友请求的状态(accepted-pending) 我正在使用此代码

let users = await User.find().select('-password').populate({ path: 'friend.$.friend_id' ,  select: 'name rate' })

当我尝试使用这条路线的邮递员时 我只得到每个用户和朋友的状态,没有每个朋友的名字 - 率

我怎样才能得到每个用户和他们朋友的信息?

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    尝试不使用.$,如下所示:

    let users = await User.find().select('-password').populate({ path: 'friend.friend_id',  select: 'name rate' })
    

    【讨论】:

      猜你喜欢
      • 2014-04-22
      • 2020-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多