【问题标题】:I'm unable to push my array to mongodb document using node.js我无法使用 node.js 将我的数组推送到 mongodb 文档
【发布时间】:2020-12-16 08:51:50
【问题描述】:

在我之前的 html 代码中,当我提交它时,它会向 /comment/:id 发送一个帖子,然后网站崩溃并输出 MongoError: Unsupported projection option: $push: { comment: {内容:“gfdghd”} } 在我的控制台中。我不知道如何解决它,我希望我能在这个问题上得到一些帮助,因为我是 web 开发的初学者。

我希望通过将包含 req.body 的数组推送到某个 mongodb 数组默认集合中,它可以在其中找到父帖子 _id。如果需要我详细说明,请询问,谢谢。

这是我的代码:

app.js

const Post = require("./models/Post");

mongoose
  .connect("secret", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
    useFindAndModify: true,
  })
  .then(() => {
    console.log("connected to mongodb cloud! :)");
  })
  .catch((err) => {
    console.log(err);
  });

app
.post("/comment/:id", authenticateUser, async (req, res) => {

  const content = req.body;

  // checks for missing fields
  if (!content){
    return res.send("Please enter all the required credentials!");
  }

  //This is where I tried to match and then push it to mongodb
  Post.update({"_id": ObjectId(req.params.id) }, {
    $push: {
      comment: content,
    }
  }, function (error, success) {
    if (error) {
        console.log(error);
    } else {
        console.log(success);
    }
});

 }) 

发布猫鼬模式

Post.js

const mongoose = require("mongoose");

const PostSchema = new mongoose.Schema({

  title: {
    type: String,
    required: true,
  },
  content: {
    type: String,
    required: true,
  },
  postedAt: {
    type: String,
    default: new Date().toString()
  },
  postedBy: {
    type: String,
  },
  warned: {
    type: String,
  },
  comment: [String]
});

module.exports = new mongoose.model("Post", PostSchema);

除数组功能外,其他一切都有效。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    我认为有一些错误,你没有await请求并且你在查询时输入"_id"而不是_id。 你也可以这样做的另一种方法是使用findByIdAndUpdate 方法。

    await Post.findByIdAndUpdate(req.params.id, {
      $push: {
        comment: content,
      },
      function(error, success) {
        if (error) {
          console.log(error);
        } else {
          console.log(success);
        }
      },
    });
    

    【讨论】:

    • 感谢您的反馈,但我现在在控制台中收到此错误Cast to string failed for value "{ content: 'test' }" at path "comment",您的方法确实适用于字符串。但我不知道为什么在 comment: content content const 返回一个错误,也许我不确定。
    • 我说你想将对象 {content: 'test} 存储在集合中是否正确?尝试将mongoose.Schema 下的“评论”类型改为Object
    • 没问题!很高兴我能帮忙:)
    猜你喜欢
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 2016-12-26
    • 1970-01-01
    • 2014-08-05
    • 2017-04-01
    • 1970-01-01
    相关资源
    最近更新 更多