[英]How to update Data in MongoDB when checked body is selected
当我选中复选框而不提交任何表单时,如何更新 MongoDB 中的数据。
我的架构
const userSchema = new mongoose.Schema({
name: {
type: String,
trim: true,
},
todos: [
{
task: {
type: String,
trim: true,
required: 'Please Enter your Task',
},
dueDate: {
type: Date,
default: new Date(+new Date() + 3 * 24 * 60 * 60 * 1000),
},
dueTime: String,
done: {
type: Boolean,
default: false,
},
},
],
});
我想更新todos
数组中的done
元素。
我试图做到这一点。
主客户端 JavaScript
$(document).ready(function () {
$('.todo--checkbox').change(function () {
let isChecked;
if (this.checked) {
isChecked = true;
$.ajax({
url: '/todo/' + this.value,
type: 'PUT',
data: { done: true },
});
} else {
isChecked = false;
$.ajax({
url: '/todo/' + this.value,
type: 'PUT',
data: { done: false },
});
}
});
});
在前端,我将复选框的值设置为 object 的_id
。
/routes/index.js在这里我正在处理我的路线
router.put('/todo/:id', todoControllers.checkStatus);
最后我在我的todoCONtroller.js中处理那个控制器
exports.checkStatus = async (req, res) => {
try {
const user = await User.aggregate([
{ $unwind: '$todos' },
{ $match: { 'todos._id': req.params.id } },
]);
// res.json(user);
console.log(user);
} catch (err) {
console.log('error: ', err);
}
};
但是我的控制台中没有任何user
。
请告诉我哪里错了。
您不需要使用聚合。 您可以使用$elemMatch
来做到这一点
const user = await User.find({
todos: { $elemMatch: { _id: req.params.id } },
});
有关更多信息,请阅读文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.