【问题标题】:How to handle circular dependencies in mongoose?如何处理猫鼬中的循环依赖关系?
【发布时间】:2020-11-11 05:58:23
【问题描述】:

我的应用程序中有以下代码

const citySchema = new Schema({
cityName: {
    type: String,
    required: true,
  },
  citizen:[{
      type: Schema.Types.ObjectId,
      ref: "Citizen",
  }],
});
module.exports = mongoose.model("City", citySchema);


const citizenSchema = new Schema({
  citizenName: {
    type: String,
    required: true,
  },
  city:{
      type: Schema.Types.ObjectId,
      ref: "City",
  },
});

module.exports = mongoose.model("Citizen", citizenSchema);

router.post('/', (req, res) => {
      // req.body.cityName
      // req.body.citizenName
})

在我的 POST 请求中,我收到了不存在的城市名称(新城市)和公民名称(新公民)。但我希望这两个模式都能正确更新。

  • 城市应包含公民参考
  • 公民应包含城市参考

我该怎么做?请帮忙

【问题讨论】:

    标签: javascript express mongoose mongoose-schema


    【解决方案1】:

    我认为您最好通过数据模型中的 pre-hook 中间件应用引用,而不是这样做。

    代码应该是这样的:

    const citySchema = new Schema({
    cityName: {
        type: String,
        required: true,
      },
      citizen:[{
          type: Schema.Types.ObjectId,
          ref: "Citizen",
      }],
    });
    
    // Query middleware to populate the 'citizen' attribute every time the 'find' function is called.
    citySchema.pre(/^find/, function (next) {
      this.populate('citizen');
      next();
    });
    
    module.exports = mongoose.model("City", citySchema);
    
    const citizenSchema = new Schema({
      citizenName: {
        type: String,
        required: true,
      },
      city:{
          type: Schema.Types.ObjectId,
          ref: "City",
      },
    });
    
    citizenSchema.pre(/^find/, function (next) {
      this.populate('city');
      next();
    });
    
    module.exports = mongoose.model("Citizen", citizenSchema);
    

    如果您只想选择 ID 而不是“完整数据”,您可以这样做,例如:

    citizenSchema.pre(/^find/, function (next) {
      this.populate({
        path: 'city',
        select: '_id',
      });
      next();
    });
    

    解释:

    • 这样,每次调用Mongoose的findByIdAndUpdatefindfindOne等函数时,引用的数据都会出现在citycitizen属性中。这实际上比每次有新数据都更新更有效。
    • populate 方法用于使用来自另一个数据模型的数据填充属性。
    • 我插入到populate 方法中的对象用于获取模型的“名称”(在path 中),并用于从引用的模型中选择要获取的数据类型。在这种情况下,我只想取_id 属性。

    【讨论】:

      猜你喜欢
      • 2014-01-28
      • 1970-01-01
      • 1970-01-01
      • 2014-10-17
      • 2013-12-21
      • 2021-01-23
      • 1970-01-01
      • 2016-05-02
      • 1970-01-01
      相关资源
      最近更新 更多