mongodb - 更新 Mongoose 中的对象数组
问题描述
我无法处理更新数据库中的对象数组,尝试了很多选项但没有任何效果。我很确定答案是显而易见的,但从星期三开始我就无法处理它。这是我的kitSchema:
const kitSchema = new mongoose.Schema({
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
kit: {
type: Array,
required: true,
},
profiles: {
type: Array,
required: true,
},
});
module.exports = mongoose.model("Kit", kitSchema);
所有用户都有自己的文档,其中也有配置文件。我想通过传递用户 ID 和配置文件 ID 来更新单个配置文件。数据示例:
_id: 1,
email: "abc@mail",
password: "abc",
profiles: [
{
id: 1,
name: John
},
]
这是我最新的解决方案,但不起作用:
router.put("/profile/:id", async (req, res) => {
let kit = await Kit.findById(req.params.id, (error, data) => {
if (error) {
console.log(error);
} else {
console.log(data);
}
});
try {
await kit.profiles.findOneAndUpdate(
{ id: req.body.id },
{ name: req.body.name },
{ new: true },
(error, data) => {
if (error) {
console.log(error);
} else {
console.log(data);
}
}
);
try {
res.status(202).json({ message: "Changed" });
} catch (err) {
res.status(400).json({ message: err });
}
} catch (err) {
res.status(400).json({ message: err });
}
});
你能帮我解决这个问题吗?
解决方案
与往常一样,经过几天的尝试,我在提问 10 分钟后得到了答案。这是我想出的:
router.put("/profile/:id", async (req, res) => {
await Kit.findOneAndUpdate(
{ _id: req.params.id, profiles: { $elemMatch: { id: req.body.id } } },
{
$set: {
"profiles.$.name": req.body.name,
"profiles.$.profilePicture": req.body.profilePicture,
},
},
{ new: true, safe: true, upsert: true },
(error, data) => {
if (error) {
console.log(error);
} else {
console.log(data);
}
}
);
try {
res.status(202).json({ message: "Changed" });
} catch (err) {
res.status(400).json({ message: err });
}
});
推荐阅读
- python - Matlab 错误:找不到 Qt 平台插件“windows”
- javascript - 如何在 JavaScript 中获取匹配的正则表达式内容?
- kubernetes-helm - 我应该添加什么 helm 存储库?
- gremlin - Gremlin 查询适用于 TinkerGraph、JanusGraph 和 Neo4j,但不适用于 DSE Graph 6.8.1
- html - 我想用 span 标签触发点击事件但没有响应
- ms-access - 在设计视图中拖动以重新定位或调整控件的大小不具有平滑效果
- swiftui - 将地图放在另一个视图 Swift UI 上方
- javascript - Fullcalender V5 如何获取事件的 ResourceId
- c# - 在哪里可以找到 .Net Core 字符串扩展方法“Substring”的源代码?
- javascript - 我可以同时设置.State 和 Sort 吗?