Search code examples
expressmongoosepopulate

How to push an object created on mongoose to populate another schema


I have two models on MongoDb, one for users and the other for events. Once the user has created an account and signed in, it shows the protected page where events can be added to their own profile. I'm trying to use populate("events") to reference the events schema to show on the user schema. And also $push to push the event to the user after being created. The results are: The event is created just fine, but nothing gets pushed to the events array on the users model. Using postman to see the user, it shows the events array empty, and the response I'm getting is 200 with an empty object. What am I missing here? It is my first time associating schemas on MongoDb, and cannot get it working. Any help is highly appreciated.

I have tried adding a callback function after { new: true }, also, {safe: true, upsert: true}, but nothing changes.

Here is some of my code:

Users model:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const userSchema = new Schema({
  username: { type: String, required: true },
  firstName: { type: String, required: true },
  lastName: { type: String, required: true },
  phone: { type: String },
  password: { type: String },
  email: { type: String, required: true },
  events: [{ type: Schema.Types.ObjectId, ref: "Event" }]
});

const User = mongoose.model("User", userSchema);

module.exports = User;

Events Model:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const eventSchema = new Schema({
  title: { type: String, required: true },
  start: { type: Date, required: true },
  end: { type: Date, required: true },
  appointment: { type: String, required: true }
});

const Event = mongoose.model("Event", eventSchema);

module.exports = Event;

Route to create the events and then try to push the created object to the user's schema:

router.post("/users/:_id", function(req, res) {
  Event.create({
    title: req.body.title,
    start: req.body.start,
    end: req.body.end,
    appointment: req.body.appointment
  })
    .then(function(dbEvent) {
      return User.findOneAndUpdate(
        { _id: req.params._id },
        {
          $push: {
            events: dbEvent._id
          }
        },
        { new: true }
      );
    })
    .then(function(dbUser) {
      res.json(dbUser);
    })
    .catch(function(err) {
      res.json(err);
    });
});

Get one User, but it returns the user with an empty array for events.

router.get("/users/:_id", (req, res) => {
  return User.findOne({
    _id: req.params._id
  })
    .populate("events")
    .then(function(dbUser) {
      if (typeof dbUser === "object") {
        res.json(dbUser);
      }
    });
});

Thanks in advance.


Solution

  • The issue was that I had events routes and user routes in separate files, and I had forgotten to import the User model into the events routes: const User = require("../../models").User;