Search code examples
node.jsmongodbmongoosemongoose-schema

How do i request the newly created model with mongoose and Node.js?


I´m creating a sport site where Users can create Teams. I want the new Team created to be automatically pushed into the Users membership and leadership arrays. But I can't figure out how to request the newly created Team as shown in the code below:

const Team = require('../models/Team.js')
const path = require('path')

module.exports = async (req,res)=>{
   await Team.create({
        ... req.body,
        teamName: req.body.teamname ,
        sportType: req.body.sporttype,
        description: req.body.description,
        location: req.body.location,
        members: [req.session.userId],
        leaders: [req.session.userId]
    });


        const user = await req.session.userId;
        const teams = //Request newly created Team
        await user.leadership.push(teams)
        await user.membership.push(teams)
        await user.save()
    res.redirect('/')

}

Here is the Schema for User:

const UserSchema = new Schema({
    username: {
        type: String,
        required: true,
        unique: true 
    },
    password: {
        type: String,
        required: true
    },
    membership: [{ type: Schema.Types.ObjectId, ref: 'Team' }],
    leadership: [{type: Schema.Types.ObjectId, ref: 'Team'}]
});

Here is the Schema for Team:

const TeamSchema = new Schema({
    teamName: String,
    sportType: String,
    description: String,
    location: String,
    members: [{ type: Schema.Types.ObjectId, ref: 'User' }],
    leaders: [{type: Schema.Types.ObjectId, ref: 'User'}]
})


Solution

  • module.exports = async (req,res)=>{
        const user = User.findById(req.session.userId)
        const teams = await Team.create({
            ... req.body,
            teamName: req.body.teamname ,
            sportType: req.body.sporttype,
            description: req.body.description,
            location: req.body.location,
            members: [req.session.userId],
            leaders: [req.session.userId]
        });
        await user.leadership.push(teams)
        await user.membership.push(teams)
        await user.save()
        res.redirect('/')
    }
    

    Try this. Also, the better approach will be to create different functions for creating the object and then calling it here.