gpt4 book ai didi

node.js - Mongoose 验证字段在保存和更新时执行

转载 作者:太空宇宙 更新时间:2023-11-04 01:54:54 24 4
gpt4 key购买 nike

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

我的架构和代码如下所示。

架构

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});
});
});

最佳答案

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

我忽略更新的条目。

关于node.js - Mongoose 验证字段在保存和更新时执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48353385/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com