javascript - Mongoose 更新子文档
问题描述
如何在猫鼬中更新子文档:
这是我的 JSON 数据
[
{
_id: "60215bb12390573490fb30c4",
publishedAt: "2021-02-08T15:41:28.562Z",
comments: [
{
messageAt: "2021-02-08T15:47:04.197Z",
_id: "60215d92f16e9f208c8663a1",
message: "beautiful picture",
userId: "600c26312c1e41372015e834",
},
{
messageAt: "2021-02-09T13:55:49.414Z",
_id: "60229495e285843da095f84e",
message: "wonderful view",
userId: "600c26312c1e41372015e834",
},
]
}
]
这是帖子架构。
const postSchema = new mongoose.Schema({
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required:
true },
photos: [{
type: String,
required: true
}],
description: {
type: String,
required: true
},
publishedAt: {
type: Date,
default: new Date()
},
likes: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
comments: [
{
message: { type: String, required: true },
messageAt: { type: Date, default: new Date() },
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User',
required: true },
}
]
});
这是 NodeJs 的一部分
router.patch('/comment/:postId/:commentId', auth, async (req, res) => {
try {
const { postId, commentId } = req.params;
const post = await Post.findById(postId);
if (!post) return res.status(400).send('Invalid Post');
post.comments.update(
{ _id: commentId },
{
$set: { message: req.body.message }
}
)
res.send('Comment updated successfully');
} catch (error) {
res.status(400).send(error.message);
}
});
**
我在 Postman 中得到了这个回复: post.comments.update 不是它接受 post.update 的函数,但这不是我想要的,因为属性消息在每个 post 对象的子文档中,请提供任何帮助
**
解决方案
您应该在模型“Post”而不是它的实例“post”上运行Model.update()方法。这里回答了一个类似的问题。
推荐阅读
- c# - 我可以通过动作选择 Selenuim 中的元素吗?
- reactjs - 从 React 到 Web API 的 MSAL 身份验证和授权
- powershell - Import-PfxCertificate 未将证书保存在指定的系统存储位置
- flask - 获取任务创建者的名字,创建时间
- c++ - 如何在 C++ 中使用 cpprestsdk POST json 数据并从本地服务器获取响应
- mysql - mysqldump 版本不匹配 - 从 Mysqlworkbench 导出时
- python - 硒滚动和点击循环
- javascript - CF11 与 CF2018:CFGRID 绑定错误,未找到元素
- module - 为什么这个 IronPython 模块路径不可见?
- c - 尽管有适当的数据类型,随机 i 字符仍被打印到我的字符串哈希表中