[英]How to create sub document in mongoose? MongoDB, NodeJS
我正在嘗試將一組評論實現為子文檔,在我的主要帖子文檔中,我是 js 和 mongoose 的新手,雖然我嘗試了 updateOne,但它正在工作,但如果我使用 save 參數,它就不起作用,並且如果我添加另一條評論,該評論將被替換,但不會添加為另一條評論。 如果我的問題很愚蠢,那是因為我很新,請幫幫我。 我的文檔的圖像
我試過的代碼:
此代碼有效,但正如我所說,每當發表新評論時,它都會替換:
//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");
}
});
我的 model 文件:
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);
您使用了錯誤的更新運算符。 如果要將元素添加到數組中,請使用$push
運算符。 這將更新數組,而$set
只會設置您提供的值,從而覆蓋以前的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.