【问题标题】:Solved: How to create sub document in mongoose? MongoDB, NodeJS已解决:如何在 mongoose 中创建子文档? MongoDB、NodeJS
【发布时间】: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


【解决方案1】:

您使用了错误的更新运算符。如果要将元素添加到数组中,请使用 $push 运算符。这将更新数组,而$set 只会设置您提供的值,从而覆盖以前的值。

【讨论】:

  • 我不是要更新,我想第一次发评论,不知道用哪个,我在保存实例中用$push替换了$set,但它的不工作。你能告诉我我做错了什么吗?
  • 我建议您将默认值指定为空数组,然后您可以随时使用 push 运算符添加项目,而无需关心这是第一次还是任何时候
  • 非常感谢您的帮助,问题已经解决了。
  • 如果有帮助,请将答案标记为正确
猜你喜欢
  • 1970-01-01
  • 2017-03-15
  • 2019-06-09
  • 2015-03-27
  • 2012-10-13
  • 2020-01-19
  • 2014-02-04
  • 1970-01-01
  • 2015-07-20
相关资源
最近更新 更多