如何在猫鼬中创建子文档? MongoDB, 节点
How to create sub document in mongoose? MongoDB, NodeJS
我正在尝试将一组评论作为子文档实现,在我的主要帖子文档中,我是 js 和 mongoose 的新手,当我尝试 updateOne 时,它可以工作,但如果我使用它就不起作用保存参数,如果我添加另一条评论,该评论将替换但不会添加为另一条评论。如果我的问题很愚蠢,那是因为我很新,请帮助我。 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);
您使用了错误的更新操作符。如果要将元素添加到数组,请使用 $push
运算符。这将更新数组,而 $set
只会设置您提供的值,从而覆盖以前的值。
我正在尝试将一组评论作为子文档实现,在我的主要帖子文档中,我是 js 和 mongoose 的新手,当我尝试 updateOne 时,它可以工作,但如果我使用它就不起作用保存参数,如果我添加另一条评论,该评论将替换但不会添加为另一条评论。如果我的问题很愚蠢,那是因为我很新,请帮助我。 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);
您使用了错误的更新操作符。如果要将元素添加到数组,请使用 $push
运算符。这将更新数组,而 $set
只会设置您提供的值,从而覆盖以前的值。