具有isActive:Boolean的用户模型
单击按钮后,将重定向到路由并从params中找到具有ID的用户。
找到用户后,它将检查isActive的值。
如果该值不为true,则将其更改为false或将其更改为true
<form action="/admin/user/<%= user._id %>/status?_method=PUT" method="POST">
<button type="submit" class="btn btn-success btn-group-sm"><i class="fas fa-check-circle"></i></button>
</form>
将req作为PUT发送到路由的按钮
const mongoose = require("mongoose");
const passportLocalMongoose = require("passport-local-mongoose");
const UserSchema = mongoose.Schema({
name: String,
mobile: String,
gender: String,
username: String,
password: String,
isActive: {
type: Boolean,
default: true
},
created: {
type: Date,
default: Date.now()
}
});
UserSchema.plugin(passportLocalMongoose);
const User = new mongoose.model("user", UserSchema);
module.exports = User;
路由以查找并更改isActive的值
router.put("/admin/user/:id/status", (req, res) => {
User.findById(req.params.id, (err, foundUser) => {
console.log(foundUser.isActive);
if (err) {
console.log(err);
} else if (foundUser.isActive == false) {
User.update({_id: req.params.id}, {$set: {isActive: true}});
res.redirect("/admin/users-details");
} else {
User.update({_id: req.params.id}, {$set: {isActive: false}});
res.redirect("/admin/users-details");
}
});
});
答案 0 :(得分:0)
在模型isActive
中,字段类型为Boolean
,但您像字符串一样检查它:
else if (foundUser.isActive !== "true")
更改else if(foundUser.isActive)
您还可以在一个mongodb查询中执行查找和更新用户的操作,如下所示:
User.findOne({ _id: req.params.id }, function(err, user) {
user.isActive = !user.isActive;
user.save(function(err, updatedUser) {
...
});
});
答案 1 :(得分:0)
尝试等到更新过程在重定向页面之前抛出结果后,通过该示例,您可以看到尝试更新记录时发生的情况:
router.put("/admin/user/:id/status", (req, res) => {
User.findById(req.params.id, (err, foundUser) => {
console.log(foundUser.isActive);
if (err) {
console.log(err);
return res.redirect("/admin/users-details?error=" + err.toString());
}
User.update({ _id: foundUser._id }, { $set: { isActive: !foundUser.isActive } }, (err2, result) => {
console.log(err, result);
res.redirect("/admin/users-details");
});
});
});