javascript - 选择检查主体时如何更新 MongoDB 中的数据
问题描述
当我选中复选框而不提交任何表单时,如何更新 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,
},
},
],
});
我想更新数组中的done
元素todos
。
我试图做到这一点。
主客户端 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 },
});
}
});
});
在前端,我已将复选框的值设置为_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 } },
});
有关更多信息,请阅读文档
推荐阅读
- if-statement - 如果为 false,则在 tickscript 中不执行任何操作
- wiremock - Spring Cloud Contract消费者端测试返回404
- entity-framework - EF Core 第二个对象引用生成循环依赖
- webpack - 如何使用 webpack5 的 'asset/resource' 和 `ImageMinimizerPlugin` 镜像源目录的文件结构?
- sql-server - 尝试使用参数和多个连接创建存储过程
- mongodb - MongoDB - 来自两个集合的猫鼬数据
- python - 如何在 discord.py 中制作 akinator 命令?
- python - Spyder修改模板template.py日期格式
- python - Selenium 错误 - 它没有输入我的名字
- c - 在linux中使用makefile生成可执行文件