【问题标题】:Mongoose validate field execute in both save and update timeMongoose 验证字段在保存和更新时间执行
【发布时间】:2018-06-29 10:04:31
【问题描述】:

我在 unique name 的猫鼬模式中使用验证现在在有人更新该记录时遇到问题它不允许用户更新,因为数据库中已经有一个条目。

我有如下架构和代码。

架构

let mongoose = require('mongoose'),
    Schema = mongoose.Schema;

let pTSchema = mongoose.Schema({
    type: {
        type: String,
        required: true,
        validate: {
          validator: function(v, cb) {  
            v = v.toLowerCase();
            PT.aggregate([  // Query for validate type should be unique if already exist than through error.
                {
                    $addFields:{
                        lowerCase: { $toLower: "$type" }
                    }
                },
                {
                    $match:{
                        lowerCase: v
                    }
                }
            ], function(err,docs){
                console.log(docs, v);
                cb(docs.length == 0);
            });
          },
          message: 'p already exists!'
        }
    }
});

module.exports = PT = mongoose.model('pt', pTSchema);

插入新记录。

// Working as expected with validation
var newPT = new PT();
newPT.type = req.body.type;
newPT.save(function(err) {
   if (err)
      return res.status(400).send({ status: false, message: JSON.stringify(err) })
   return req.res.status(200).send({status:true, data: newPT});
});

更新记录。

// While update single record it also executes schema validate and won't give permission to save.
// Please give me some suggestion on this.

PT.findOne({ _id : where }, function(err, responsePT) {
    if (!PT) {
        return res.status(500).send({ status: false, message: "ERROR" });
    }
    responsePT.type = req.body.type;
    responsePT.save(function(err) {
        if (err)
            return res.status(400).send({ status: false, message: JSON.stringify(err) })
        return req.res.status(200).send({status:true, data: responsePT});
    });
});

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    最后,我没有得到任何解决方案,所以我用.pre('save', 更新了我的代码,它解决了我的问题。

    我忽略更新的条目。

    【讨论】:

      猜你喜欢
      • 2016-11-17
      • 2020-12-30
      • 1970-01-01
      • 2017-01-03
      • 2017-09-23
      • 2017-10-06
      • 2016-05-02
      • 1970-01-01
      • 2013-08-06
      相关资源
      最近更新 更多