【问题标题】:Mongoose auto fill data by searching in referenceMongoose 通过参考搜索自动填充数据
【发布时间】:2020-05-08 02:25:17
【问题描述】:
const UserSchema = new Schema(
  {
    referrals: {
      ref: 'User',
      type: [mongoose.Schema.Types.ObjectId],
    },

    referredBy: {
      ref: 'User',
      type: mongoose.Schema.Types.ObjectId,
    },
  }
);

我希望 Mongoose 在 referredBy 参考中找到当前用户 _id 的用户。

换句话说,例如:找到所有在其referredBy字段中具有'_IDOfSpecificUser'的用户,并将所有找到的用户放入referrals的数组中,其中用户的_id为'_IDOfSpecificUser'

如何在猫鼬中处理这个问题?

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    最简单的是使用find

    User.
      find({ "referredBy" : "xxxxxxxxxxxx" }).
      exec(function (err, users) {
        if (err) return handleError(err);
        console.log('The users are an array: ', users);
      });
    

    参考https://mongoosejs.com/docs/populate.html

    如果要将波纹管函数转换为UserSchema中的静态方法,请参考https://mongoosejs.com/docs/api.html#schema_Schema-statichttps://mongoosejs.com/docs/2.7.x/docs/methods-statics.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-04
      • 1970-01-01
      • 1970-01-01
      • 2016-05-31
      • 2021-03-24
      • 1970-01-01
      • 2021-02-24
      • 2021-09-09
      相关资源
      最近更新 更多