Filippo Rivolta
Filippo Rivolta

Reputation: 55

Finding _id of user just created in a route

I am making a rapid prototype of a MERN application, I have a backend question: I have a User model and a Category model, when a user sign up, I need to fill the category model with some basic informations exported from an object the user can edit later. I would like to assign every category a ref to the just created account id. The problem is I don't understand how I can retrieve the just created user id. Here is my route (yes is not refactored, sorry):

// @route   POST api/users/register
// @desc    Register user
// @access  Public
router.post('/register', (req, res)=>{
    //Validate req.body
    const {errors, isValid} = validateRegisterInput(req.body);
    //Check validation 
    if(!isValid){
        return res.status(400).json(errors); 
    }

    User.findOne({ email: req.body.email })
        .then(user => {
            if(user){
                errors.email = 'Email already exists';
                return res.status(400).json(errors)
            } else {
                const avatar = gravatar.url(req.body.email, {
                    s: '200', //Size
                    r: 'pg',  //Rating
                    d: 'mm'   //Default
                });
                const newUser = new User({
                    name: req.body.name,
                    email: req.body.email,
                    avatar,
                    password: req.body.password
                });
                //Hash the password and save
                bcrypt.genSalt(10, (err, salt)=>{
                    bcrypt.hash(newUser.password, salt, (err, hash)=>{
                        if(err) throw err;
                        newUser.password = hash;
                        newUser.save()
                            .then(user => res.json(user))
                            .catch(err => console.log(err))
                    })
                });
                //Fill user categories with default categories
                defaultIcons.map((icon) => {
                    const newCategory = new Category ({
                        name: icon.name,
                        type: icon.type,
                        icon: icon.icon
                    })
                    newCategory.save();
                });
            }
        })
});    

And this is the Category Schema:

//Create Schema
const CategorySchema = new Schema({
    //Every account is associated with actual User schema by id
    user: {
        type: Schema.Types.ObjectId,
        ref: 'users'
    },
    name: {
        type: String,
        required: true
    },
    type: {
        type: String,
        required: true
    },
    icon: {
        type: String,
        required: true
    }
})

What would be the best solution for this? Is it better to have a separated schema for the categories like I am doing or I can implement an array of objects field in the User schema?

Upvotes: 0

Views: 28

Answers (1)

Arootin Aghazaryan
Arootin Aghazaryan

Reputation: 848

The part where you do

if(err) throw err;
    newUser.password = hash;
    newUser.save()
        .then(user => res.json(user))
        .catch(err => console.log(err))

you have the user in your resolved promise. you can just

const newCreatedUserID = user._id

to get the just created user ID.

Upvotes: 1

Related Questions