软删除猫鼬数据库中的文档

时间:2020-04-21 10:49:50

标签: mongodb mongoose

我有一个创建优惠券代码的功能。我在一个字段上添加了一个到期日,该到期日将自动按照所述日期使优惠券到期。为此,我使用了猫鼬的TTL属性。但是我的问题是它将从数据库中永久删除文档。

以下是我的架构和控制器:

const promotionalCodeSchema = new schema({

    promoCodeName: { 
        type: String,
    },
    promoCodeType: String,
    expired: {
        type: Boolean,
        default: false
    },
    amount: String,
    isActive: { 
        type: Boolean, 
        default: true 
    }, 
    user_id: ObjectId,
    expirationDate: {
        type: Date,
        expires: 0,
        unique: true
    }
}, {
    timestamps: true
});


async createPromoCode(req, res) {
    let body = req.body;

    try {
      let newObjBody = {
        promoCodeName: "",
        promoCodeType: "",
        amount: "",
        expirationDate:{
            expires:0
        }
      };

      newObjBody.amount = body.promoAmount;
      newObjBody.isActive = body.promoActive;
      newObjBody.promoCodeName = PromotionalCodeController.generateCoupon();

      newObjBody.promoCodeType = body.promoCodeType;

      let days = parseInt(body.promoExpiry.replace(/[^\d]+/g, ""));
      newObjBody.expirationDate = new Date(Date.now() + (days * 24 * 3600 * 1000));

      const promotionalcodeschema = new PromotionalCodeSchema(newObjBody);
      await promotionalcodeschema.save((err, result) => {
        if (err) {
          res.status(400).json({err})
        } else {
          res.status(201).json(result)
        }
      });
    } catch (error) {
      console.log(error);
    }
  }

一切都很好,但是当到达到期日期时,我只需要将文档的属性更新为“ expireed:true”,而不是将其从数据库中永久删除。

请帮助我提出实现此目标的正确方法。

0 个答案:

没有答案
相关问题