我正在尝试更新MongoDB中的一个集合中的现有文档.Mongoose正在抛出验证错误消息“:
"local_transport_details validation failed: contact.residingcountry: Path `contact.residingcountry` is required.,
contact.postalCode: Path `contact.postalCode` is required.,
contact.city: Path `contact.city` is required.,
contact.addressLine1: Path `contact.addressLine1` is required.,
name: Path `name` is required.,
providerID: Path `providerID` is required."
如果调用transportSchema.save函数,脚本可以正常工作。
每次编辑后是否必须保存文档?如果是,请帮助我摆脱此验证错误?
模型 -
var localTransportSchema = new Schema({
providerID: { type: Number, required: true, trim: true, unique: true },
name: { type: String, required: true, trim: true },
contact: {
addressLine1: { type: String, required: true },
addressLine2: { type: String, required: false },
city: { type: String, required: true },
postalCode: { type: Number, required: true },
primaryContactNumber: {type: Number,required: true},
secondaryContactNumber: {type: Number,required: false},
serviceActiveFlag: { type: String, required: false, enum: ['Y', 'N'] },
},
vehicle: [{
vehicleType:{ type: String, required: false, enum: ['sedan', 'hatchback', 'suv', 'mpv', 'luxury'] },
activeFlag: { type: String, required: false, enum: ['Y', 'N'] },
}]
});
控制器代码
module.exports.updateLocalTransportVendorDtls = function (req, res) {
var transportSchema = new transportModel();
new Promise(function (resolve, reject) {
checkForNewVehicleType(req, function (doc) {
resolve(doc)
})
})
.then(function (doc) {
var updateJustServiceDtls = doc.split(/\|/)[2];
if (updateJustServiceDtls == 'true') { /* To update service details for the same vendor */
return updateJustServiceDetailsOnly(req, res)
}
}).then(function () {
transportSchema.save(function (error) {
if (error) {
logger.error("Error while updating record in transport details collection: - " + error.message)
return res.status(500).json({ "Message": error.message.trim() });
}
})
}).catch(function (err) {
return res.json({ "Message": err.message });
});
}
功能 -
var updateJustServiceDetailsOnly = function (req, res) {
var promise = new Promise(function (resolve, reject) {
transportModel.findOneAndUpdate({ "name": req.body['providerName'], "contact.postalCode": parseInt(req.body['postalCode']) },
{
"contact.addressLine1": req.body['addressLine1'],
"contact.addressLine2": req.body['addressLine2'],
"contact.city": req.body['city'],
"contact.postalCode": parseInt(req.body['postalCode']),
"contact.primaryContactNumber": parseInt(req.body['primaryContactNumber']),
"contact.serviceActiveFlag": req.body['serviceActiveFlag'],
}, { returnOriginal: false, upsert: true }, function (err, doc) {
if (err) {
return reject(res.status(409).json({
"Message": "Error while updating transport details for provider " + req.body['providerName'] + " in transport details table"
}));
}
resolve();
});
})
return promise;
}