2

I'm not able to get data from mongodb. When i run server it is showing error like this :

node:15171) UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "${this.groupId}" at path "_id" for model "Group"

    export const getGroup = async (req, res) => { 
        const {groupId} = req.params;

        if (!groupId) { 
            return res.status(400).json({ 
                error: true, 
                message: 'You need to provided a group id' 
            }); 
        }

        // Search for see if group exist 
        const group = await Group.findById(groupId);

        if (!group) { 
            return res.status(400).json({ 
                error: true, 
                message: 'Group not exist' 
            }); 
        }

        try { 
            return res.status(200).json({ 
                error: false, 
                meetups: await Meetup.find({ group: groupId }).populate('group', 'name')
            }); 
        } catch (e) { 
            return res.status(400).json({ 
                error: true,
                message: 'Cannot fetch meetup' 
            }); 
        } 
    };
vimuth
  • 5,064
  • 33
  • 79
  • 116
susan
  • 23
  • 4
  • please post the group and meetup schema also. – Vikash_Singh May 29 '19 at 05:50
  • import mongoose, { Schema } from 'mongoose'; const GroupSchema = new Schema({ name: { type: String, required: true, unique: true, minLength: [5, 'Name must be 5 characters long'], }, description: { type: String, required: true, minLength: [10, 'Description must be 10 characters long'], }, category: { type: String, }, meetups: [{ type: Schema.Types.ObjectId, ref: 'Meetup', }], }, { timestamps: true }); – susan May 29 '19 at 05:54
  • GroupSchema.statics.addMeetup = async function (id, args) { const Meetup = mongoose.model('Meetup'); const meetup = await new Meetup({ ...args, group: id }); const group = await this.findByIdAndUpdate(id, { $push: { meetups: meetup.id } }); return { meetup: await meetup.save(), group, }; }; export default mongoose.model('Group', GroupSchema); – susan May 29 '19 at 05:55
  • Possible duplicate of [Node.js Mongoose.js string to ObjectId function](https://stackoverflow.com/questions/6578178/node-js-mongoose-js-string-to-objectid-function) – 1565986223 May 29 '19 at 06:32

0 Answers0