0

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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

8 Comments

i tried your code but got this error UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "" at path "_id" for model "Event" while using .populate("events")
even if i use .populate("event"), then objectID is not even inserted
Could you try, populate("Event") and also, make sure you are only saving _ids to the events array? I assume your using promises instead of the callback in your snippet.
i'm using your command asyn await in my snippet now. And did try .populate("Event") but no luck
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.