【问题标题】:How to auto delete ObjectId referances in mongodb如何在 mongodb 中自动删除对象 ID 引用
【发布时间】:2021-02-19 04:17:10
【问题描述】:

当通知被删除时,我试图自动删除来自用户的通知引用

userSchema 看起来像

const mongoose = require("mongoose");

const userSchema = new mongoose.Schema({
 
  notifications: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Notification",
    },
  ],
});

module.exports = mongoose.model("User", userSchema);

通知模型如下所示

    const mongoose = require("mongoose");

const notificationSchema = new mongoose.Schema({
  type: String,
  created: {
    type: Date,
    default: Date.now,
  },
});
notificationSchema.pre("deleteOne", function (next) {
  this.model("User").deleteOne({ notifications: this._id }, next);
});
module.exports = mongoose.model("Notification", notificationSchema);

当我尝试删除通知时,我收到一个错误,看起来像

ObjectParameterError: Parameter "obj" to Document() must be an object, got User

还有一种方法可以使用 TTL 通知自动删除它[用户中通知的引用]​​

【问题讨论】:

    标签: javascript arrays mongodb mongoose mongoose-schema


    【解决方案1】:

    好的,经过几次尝试和错误。我想出了这个解决方案..

        const mongoose = require("mongoose");
    const notificationSchema = new mongoose.Schema({
      type: String,
      created: {
        type: Date,
        default: Date.now,
      },
    });
    notificationSchema.pre("deleteOne", function (next) {
      let id = this.getQuery()["_id"];
      mongoose.model("User").findOne(
        {
          notifications: id,
        },
        (err, res) => {
          const index = res.notifications.findIndex((x) => x._id == id);
          res.notifications.splice(index, 1);
          res.save();
          next();
        }
      );
    });
    module.exports = mongoose.model("Notification", notificationSchema);
    

    我可以做些改进吗?

    【讨论】:

      猜你喜欢
      • 2012-08-07
      • 1970-01-01
      • 1970-01-01
      • 2021-11-12
      • 1970-01-01
      • 2019-01-10
      • 2019-11-25
      • 1970-01-01
      相关资源
      最近更新 更多