MongoDB从body中查找,更新和验证空字段



在更新字段之前,我需要检查以下值是否不为空。 所以我按照以下方式构建,但不检索我的味精错误,也不让我更新配置文件用户。

router.post("/profileEdit/:id", ensureAuthenticated, (req, res) => {
var id = mongoose.Types.ObjectId(req.params.id);
let errors = [];
if (!req.body.firstName) {
errors.push({ text: "Please add your first name" });
}
if (!req.body.lastName) {
errors.push({ text: "Please add your last name" });
}
if (!req.body.username) {
errors.push({ text: "Please add your username" });
}
if (!req.body.email) {
errors.push({ text: "Please add you email" });
}
if (errors.length > 0) {
res.render("users/profileEdit", {
errors: errors,
firstName: req.body.firstName,
lastName: req.body.lastName,
username: req.body.username,
email: req.body.email
});
} else {
User.updateOne(
{ _id: id },
{
$set: {
firstName: req.body.firstName,
lastName: req.body.lastName,
username: req.body.username,
email: req.body.email
}
}
).then(user => {
req.flash("success_msg", "Profile Updated");
res.redirect("/users/profile/" + id);
});
}
});

如何验证每个字段的 req.body 是否为空?在此验证之后,我需要更新 mongodb 中的信息。

解决方案如下:

在其他之前,我只需要找到 _id:id,这样,由于上面的字段为空,应用程序将返回填充字段的同一页面。

router.post("/profileEdit/:id", ensureAuthenticated, (req, res) => {
var id = mongoose.Types.ObjectId(req.params.id);
let errors = [];
if (!req.body.firstName) {
errors.push({ text: "Please add your first name" });
}
if (!req.body.lastName) {
errors.push({ text: "Please add your last name" });
}
if (!req.body.username) {
errors.push({ text: "Please add your username" });
}
if (!req.body.email) {
errors.push({ text: "Please add you email" });
}
if (errors.length > 0) {
User.find(
{ _id: id },
{
firstName: 1,
lastName: 1,
username: 1,
email: 1,
password: 1,
_id: { $elemMatch: { _id: id } },
date: 1
}
).then(user => {
res.render("users/profileEdit", {
user: user
});
});
} else {
User.updateOne(
{ _id: id },
{
$set: {
firstName: req.body.firstName,
lastName: req.body.lastName,
username: req.body.username,
email: req.body.email
}
}
).then(user => {
req.flash("success_msg", "Profile Updated");
res.redirect("/users/profile/" + id);
});
}
});

最新更新