【问题标题】:how to add comments to mongoose array with node and reactjs?如何使用 node 和 reactjs 向 mongoose 数组添加注释?
【发布时间】:2021-12-22 14:34:16
【问题描述】:

所以我在尝试将 cmets 添加到我的 mongoDB 数据库中已经存在的某些数据时遇到了问题。我想这样做,以便我可以为保存在我的数据库中的每个帐户添加、删除和更新 cmets,但我不确定我做错了什么。我已经设置了我的前端来发送一条新评论和所有需要附带的数据。它成功到达我的后端,在我的后端它说它运行并保存但它没有,当我重新加载页面时,我的数据中的 cmets 数组仍然为 0。

Account.findByIdAndUpdate(
  { _id: comment.accountId },
  {
    $push: {Account: { comments: comment }},
  },
  { new: true, upsert: true }
).exec(function (err, task) {
  if (err) {
    return res
      .status(400)
      .send({ message: "Failed to add comment due to invalid params" });
  }
  console.log("successfully uploaded comment");
  return res.status(200).send(task);
});

所以我们在这里加载特定帐户,然后将新评论推送到我的猫鼬模式中的 cmets 数组。当我取出“帐户:对象并仅使用 cmets:comment 对对象进行 ahve 时,它​​说后端存在内部错误,找不到我猜的参数,这将是 cmets 数组。

我不知道为什么这会是一个问题。下面也是我的猫鼬模式。

    const AccountSchema = new Schema({
  username: {
    type: String,
  },
  name: {
    type: String,
  },
  date: {
    type: Date,
    default: Date.now,
  },
  description: {
    type: String,
  },
  latitude: {
    type: Number,
  },
  longitude: {
    type: Number,
  },
  comments: [
    {
      id: Number,
      text: String,
      type: String,
      date: Date,
      replies: [{ id: Number, text: String, type: String, date: Date }],
    },
  ],
});

我没有正确设置我的架构吗?还是我忘记在某处添加一些东西。任何帮助都会很棒,谢谢!

【问题讨论】:

  • 你不需要重复 'Account',试试 "$push: {cmets: comment }," 代替

标签: node.js reactjs mongodb mongoose mongoose-schema


【解决方案1】:

只是想发布一个更新,我改变了 findbyidandupdate 上的选项,我添加了新的和安全的并且 upsert 全部为真,然后我意识到我的主要问题是我的架构中的 cmets 数组已设置键入:字符串,而不是数组。哈哈,谢谢你们的帮助。

【讨论】:

    【解决方案2】:

    您的更新查询的$push 规范似乎是罪魁祸首。在代码中,它说:

    $push: {Account: { comments: comment }}
    

    但是您的Account 模型没有“帐户”字段可将对象推送到其中。要将新元素插入“cmets”数组,请改为:

    $push: { comments: comment }
    

    【讨论】:

    • 我刚刚尝试过,现在我收到了 400 错误请求。就像它没有在架构中找到 cmets 数组一样。它直接进入我的捕获错误。如果我的数据还没有 cmets 数组,是否需要在推送中进行设置?比如检查数组是否存在,如果存在添加注释,如果不添加数组则添加注释?
    • 不,它不需要存在 - 当你 $push 时,MongoDB 会为你创建一个空数组。检查您在回调中收到的err 错误(通过console.log 或其他方式)。我的猜测是,“new: true”会破坏事物,但您需要实际查看错误才能确定。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多