【发布时间】:2021-05-10 14:49:22
【问题描述】:
我正在尝试将一组 cmets 实现为子文档,在我的主要帖子文档中,我是 js 和 mongoose 的新手,虽然我尝试了 updateOne,但它正在工作,但如果我使用 save 则它不起作用参数,如果我添加另一条评论,评论将被替换,但不会添加为另一条评论。如果我的问题很愚蠢,那是因为我很新,请帮帮我。 image of my document
我尝试过的代码:
此代码有效,但正如我所说,每当提出新评论时,它都会被替换:
//add comment
router.post("/:id/comment", async (req, res) => {
try {
const post = await Post.findById(req.params.id);
const comment = await post.updateOne({ $set: { comments: req.body } });
res.status(200).json(comment);
} catch (err) {
res.status(500).json("error");
}
});
保存参数:
//add comment
router.post("/:id/comment", async (req, res) => {
try {
const post = await Post.findById(req.params.id);
const comment = await post.save({ $set: { comments: req.body } });
res.status(200).json(comment);
} catch (err) {
res.status(500).json("error");
}
});
我的模型文件:
const mongoose = require("mongoose");
const PostSchema = new mongoose.Schema(
{
userId: {
type: String,
require: true,
},
description: {
type: String,
max: 1000,
},
image: {
type: Array,
},
likes: {
type: Array,
default: [],
},
comments: [
new mongoose.Schema(
{
userId: {
type: String,
require: true,
},
comment: {
type: String,
default: "",
},
},
{ timestamps: true }
),
],
},
{ timestamps: true }
);
module.exports = mongoose.model("Post", PostSchema);
解决的代码;
//添加注释(将$set替换为$push)
router.post("/:id/comment", async (req, res) => {
try {
const post = await Post.findById(req.params.id);
const comment = await post.updateOne({ $push: { comments: req.body } });
res.status(200).json(comment);
} catch (err) {
res.status(500).json("error");
}
});
//模型文件(在cmets数组中添加默认值)
const mongoose = require("mongoose");
const PostSchema = new mongoose.Schema(
{
userId: {
type: String,
require: true,
},
description: {
type: String,
max: 1000,
},
image: {
type: Array,
},
likes: {
type: Array,
default: [],
},
comments: [
new mongoose.Schema(
{
userId: {
type: String,
require: true,
},
comment: {
type: String,
default: "",
},
},
{ timestamps: true }
),
{ default: [] },
],
},
{ timestamps: true }
);
module.exports = mongoose.model("Post", PostSchema);
【问题讨论】:
-
这就是 $set 的作用。你的意思是使用 $push 吗?
-
@Joe 我不知道用什么,我的要求是以数组的形式将评论文档作为子文档发布。你能告诉我我做错了什么吗?。
标签: javascript node.js mongodb mongoose mongoose-schema