Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
I';我无法使用node.js将我的数组推送到mongodb文档_Node.js_Mongodb_Mongoose - Fatal编程技术网

I';我无法使用node.js将我的数组推送到mongodb文档

I';我无法使用node.js将我的数组推送到mongodb文档,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,在我以前的html代码中,当我提交时,它会向/comment/:id发送帖子,然后网站崩溃并输出MongoError:Unsupported projection选项:$push:{comment:{content:“gfdghd”}}。我不知道如何解决这个问题,我希望我能在这个问题上得到一些帮助,因为我是web开发的新手 我希望通过将包含req.body的数组推到某个mongodb数组默认集合中,在该集合中找到父post\u id来实现这一点。如果您需要我详细说明,请询问,谢谢 这是我的代码:

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

我希望通过将包含req.body的数组推到某个mongodb数组默认集合中,在该集合中找到父post\u 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);

除了阵列功能,其他一切都正常。

我认为有一些错误,您没有等待请求,在查询时输入了
“\u id”
,而不是
\u id
。 另一种方法是使用
findbyiandupdate
方法

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

感谢您的反馈,但我现在在控制台中收到此错误,因为路径“comment”处的值“{content:'test'}”的字符串转换失败,您的方法确实可以处理字符串。但是我不知道为什么在评论中:content content const返回时出现了一个错误,这可能是我的原因,我不确定。我说您想在集合中存储对象{content:'test}对吗?尝试将
mongoose.Schema
下的“comment”类型改为
Object
。没问题!很高兴我能帮忙:)