Hi I am trying to add an event to a users profile once they click on the event. I am getting the following error – Cast to ObjectId failed for value “{ event: ‘600066640807165d042b91dd’ }” at path “event”. The route for creating a profile and for creating an event work as expected. The 600 is the id of an event that I created and I am now trying to push that event into the users profile but it is not working.
Here is my code
Profile Schema
const mongoose = require('mongoose'); const ProfileSchema = new mongoose.Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: 'user' }, event: [ { type: mongoose.Schema.Types.ObjectId, ref:'event' } ], location: { type: String, required: true, }, company: { type: String }, date: { type: Date, default: Date.now } }); module.exports = Profile = mongoose.model('profile', ProfileSchema);
Event Schema
const mongoose = require('mongoose'); const EventSchema = new mongoose.Schema({ timeOfEvent: { type: String, required: true, }, dateOfEvent: { type: String, required: true, }, title: { type: String, required: true }, location: { type: String, required: true }, speaker: { name: { type: String, required: true }, bio: { type: String, required: true }, interests: { type: String, required: true } }, date: { type: Date, default: Date.now } }); module.exports = Event = mongoose.model('event', EventSchema);
Route
// @route PUT api/profile/me/addEvent // @desc PUT current users profile // @access Private router.put('/me/addEvent', auth, async (req, res) => { const event = req.body; const profileFields = {}; if(event) profileFields.event = event; try { let profile = await Profile.findOne({ user: req.user.id }); if(profile) { profile = await Profile.findOneAndUpdate( { user: req.user.id }, { $push: {"event": event}}, { new: true }); res.status(201).send(profile); } } catch (err) { console.error(err.message); res.status(500).send('Server Error'); } });
Any help will be much appreciated.
Advertisement
Answer
you should pass an object id to event, the req.body
is a object for get objectId of event do like this
let {event} = req.body profile = await Profile.findOneAndUpdate( { user: req.user.id }, { $push: {"event": event}}, { new: true });