Insane DA
Insane DA

Reputation: 363

Only objectID is saved in the array in another model in mongodb

I have two models in my mongoDB. One is user model and one is event model. What I want to achieve is, when I will add a new event then, that event array will save to my user model's events column array. Till now, I've successfully saved that id of that event to specific user but the problem is only the **objectID** is coming not the property is showing up likeevent name,descriptions`. This is my code:

user model:

const userSchema =  mongoose.Schema({
    name: String,
    events: [
        { 
            type: Schema.Types.ObjectId, 
            ref: 'Event' 
        }
    ]
});

Event model:

const eventSchema = new Schema({
    creator: {
        type: Schema.Types.ObjectId,
        ref: 'User'
    },
    ename: {
        type: String
    },
    description: {
        type: String
    },
});

routes.js

router.post('/', (req, res) => {

  const event = new Event();
  event.creator = '5d9e1ba694f44227e1f54cc0',
  event.ename = req.body.ename;

  event.save( (err, result) => {
      if (!err)
          res.redirect('events');
      else {
          console.log('error', err);
      }
  }); 
  User.findOneAndUpdate('5d9e1ba694f44227e1f54cc0', {$push: { events: [event] }}, (err, result) => {
      if(err) {
          console.log(err);
      } else {
          console.log('event is saved');
      }
  });

});

for simplicity, I've kept my user id hardcoded. Now, how can I update the $push method of the mongodb so that the whole properties of the event is to save in the user model not only the objectID

Upvotes: 0

Views: 952

Answers (1)

Dan Starns
Dan Starns

Reputation: 3825

I think you may be getting a little confused with how you have set up your model & how mongoose Query Population works.

In userSchema, you have defined that events is an array of type Schema.Types.ObjectId and each 'Event' references a document in the eventSchema schema. Because of this, you cant expect events to be an array of Event.

However, because you have defined this reference in your schema when you query for a document, you can use the Model.Populate method.

const user = await findById("id").populate("events");

This method will find a User and for each Event will look up the Event collection to find a relating document with that ObjectID. This will return a User with the events array being populated with the corresponding Event

Upvotes: 2

Related Questions