我在 Node.js/Express 应用程序中遇到了 Mongoose 的一些问题,非常感谢您的帮助。当我尝试更新 MongoDB 中的
Restaurant
文档时,就会出现问题。我收到一条验证错误,提示 lastUpdated
字段是必需的,即使我在保存文档之前明确设置了该字段。
error Error: Restaurant validation failed: lastUpdated: Path `lastUpdated` is required.
at ValidationError.inspect (/opt/render/project/src/node_modules/mongoose/lib/error/validation.js:50:26)
at formatValue (node:internal/util/inspect:806:19)
at inspect (node:internal/util/inspect:365:10)
at formatWithOptionsInternal (node:internal/util/inspect:2304:40)
at formatWithOptions (node:internal/util/inspect:2166:10)
at console.value (node:internal/console/constructor:338:14)
at console.log (node:internal/console/constructor:383:61)
at /opt/render/project/src/dist/controllers/MyRestaurantController.js:81:17
at Generator.throw (<anonymous>)
at rejected (/opt/render/project/src/dist/controllers/MyRestaurantController.js:6:65) {
errors: {
lastUpdated: ValidatorError: Path `lastUpdated` is required.
at validate (/opt/render/project/src/node_modules/mongoose/lib/schemaType.js:1385:13)
at SchemaType.doValidate (/opt/render/project/src/node_modules/mongoose/lib/schemaType.js:1369:7)
at /opt/render/project/src/node_modules/mongoose/lib/document.js:3071:18
at process.processTicksAndRejections (node:internal/process/task_queues:85:11) {
properties: [Object],
kind: 'required',
path: 'lastUpdated',
value: undefined,
reason: undefined,
[Symbol(mongoose#validatorError)]: true
}
},
_message: 'Restaurant validation failed'
}
猫鼬架构:
const restaurantSchema = new mongoose.Schema({
user: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
restaurantName: { type: String, required: true },
city: { type: String, required: true },
country: { type: String, required: true },
deliveryPrice: { type: Number, required: true },
estimatedDeliveryTime: { type: Number, required: true },
cuisines: [{ type: String, required: true }],
menuItems: [menuItemSchema],
imageUrl: { type: String, required: true },
lastUpdated: { type: Date, default: Date.now },
});
const Restaurant = mongoose.model("Restaurant", restaurantSchema);
控制器代码:
const updateMyRestaurant = async (req: Request, res: Response) => {
try {
// Log incoming request data
console.log("Request body before update:", req.body);
const restaurant = await Restaurant.findOne({ user: req.userId });
if (!restaurant) {
return res.status(404).json({ message: "Restaurant not found" });
}
// Update fields
restaurant.restaurantName = req.body.restaurantName;
restaurant.city = req.body.city;
restaurant.country = req.body.country;
restaurant.deliveryPrice = req.body.deliveryPrice;
restaurant.estimatedDeliveryTime = req.body.estimatedDeliveryTime;
restaurant.cuisines = req.body.cuisines;
restaurant.menuItems = req.body.menuItems;
restaurant.lastUpdated = new Date();
if (req.file) {
const imageUrl = await uploadImage(req.file as Express.Multer.File);
restaurant.imageUrl = imageUrl;
}
await restaurant.save();
res.status(200).send(restaurant);
} catch (error) {
console.log("Error during restaurant update:", error);
res.status(500).json({ message: "Something went wrong" });
}
};
我希望正确设置
lastUpdated
字段,并且更新操作成功,没有任何验证错误。我尝试过以下方法:
确保在保存文档之前为
lastUpdated
分配了新的 Date()
值。
在调用
lastUpdated
确认已设置之前记录 save()
的值。
仔细检查架构以确保
lastUpdated
具有默认值并且未标记为必需。
尽管做出了这些努力,验证错误仍然存在,并且更新失败。我希望深入了解可能导致此问题的原因以及如何解决它。
问题出在下面一行:
restaurant.lastUpdated = new Date();
耶稣出生日期的默认日期
(1.1.1 00:00:00)
被认为是not defined
或empty
。将其更改为以下内容:
restaurant.lastUpdated = Date.now;