Mongoose验证字段在保存和更新时间内执行

时间:2018-01-20 06:38:14

标签: node.js mongodb mongoose mongoose-schema

我在mongoose模式中使用validate 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});
    });
});

1 个答案:

答案 0 :(得分:0)

At,Final I没有得到任何解决方案,所以我用 ServiceReference1.StockCardServicesClient sList = new ServiceReference1.StockCardServicesClient(); BindingSource StockCardList = new BindingSource(); private void Form1_Load(object sender, EventArgs e) { StockCardList.DataSource = sList.GetParticularCard(); txtID.DataBindings.Add(new Binding("Text", StockCardList, "CategoryName", true)); txtOPCOID.DataBindings.Add(new Binding("Text", StockCardList, "MainGroupName", true)); txtSubGroupID.DataBindings.Add(new Binding("Text", StockCardList, "SubGroupName", true)); txtIDNumber.DataBindings.Add(new Binding("Text", StockCardList, "IDNumber", true)); txtPartNumber.DataBindings.Add(new Binding("Text", StockCardList, "PartNumber", true)); txtDescription.DataBindings.Add(new Binding("Text", StockCardList, "Description", true)); } 更新了我的代码。它解决了我的问题。

我忽略了更新的条目。