Darius
Darius

Reputation: 7

MongoDB $push method seems to be not working

This is my User Schema, and I'm unable to add any posts.

import mongoose from "mongoose";
const { Schema } = mongoose;

const postSchema = new Schema(
  {
    userId: {
      type: String,
      required: true,
    },
    content: {
      type: String,
      required: true,
      max: 240,
    },
    sketchUri: {
      type: String,
      default: "",
    },
  },
  { timestamps: true }
);

export const userSchema = new Schema(
  {
    name: {
      type: String,
      trim: true,
      required: true,
    },
    email: {
      type: String,
      trim: true,
      required: true,
      unique: true,
    },
    password: {
      type: String,
      min: 6,
      max: 64,
      required: true,
    },
    bio: {
      type: String,
    },
    website: {
      type: String,
    },
    posts: [postSchema],
    profile_pic: {},
  },
  { timestamps: true }
);

export default mongoose.model("User", userSchema);

And here is the code to add new posts:

const post = await User.findOneAndUpdate(
        { req.params.userId },
        {
          $push: {
            posts: {
              userId: req.user.id,
              content: req.body.thought,
              sketchUri: req.body.sketch,
            },
          },
        },
        { new: true }
      ).exec();
      res.json(post);

the res.json(post) statement here returns null.

Whenever I run this code, the backend returns a 200 status code, no errors are thrown inspite of using a try-catch block but the code isn't added anywhere in the database. Why is my $push function failing?

NOTE: Also, when I run the findOneAndUpdate function as follows, it returns the correct data, so the userId is correct.

const post = await User.findOneAndUpdate({ userId }).exec();

This is when I run the above code, but when I run it with $push, it returns null.

enter image description here

Upvotes: 0

Views: 148

Answers (2)

Manasvi Mittal
Manasvi Mittal

Reputation: 250

So as we can notice that there is no field that you are matching the doc with at first place. if we assume you are matching it with the default id that mongo is providing then please use the proper matching statement in the findOneAndUpdate() method.

{id: ObjectId(req.params.id)}

Upvotes: 0

John Galt
John Galt

Reputation: 50

I see you are using findOneAndUpdate() and passing req.params.userId

You should be using findByIdAndUpdate() if you wish to pass the id as a parameter to find the user to update or change your code to be like:

const post = await User.findOneAndUpdate(
        { id: req.params.userId },
        {
          $push: {
            posts: {
              userId: req.user.id,
              content: req.body.thought,
              sketchUri: "aaaaaaa",
            },
          },
        },
        { new: true }
      ).exec();
      res.json(post);

I added id: req.params.userId if you can't see it

Upvotes: 1

Related Questions