I'm unable to push my array to mongodb document using node.js

Viewed 43

In my previous html code when I submit it sends a post to /comment/:id then the website crashes and outputs MongoError: Unsupported projection option: $push: { comment: { content: "gfdghd" } } in my console. I don't know how to solve it and I hope I can get some help on the issue as I'm a starter with web development.

I want this to work by pushing the array which includes the req.body into a certain mongodb array default collection where it finds the parent post _id. If you need me to elaborate please ask, thanks.

This is my code:

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 Mongoose Schema

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);

Everything else works but the array functionality.

1 Answers

I think there are a few mistakes, you didn't await the request and you put "_id" when querying instead of _id. Another way you could do it too would be using findByIdAndUpdate method.

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