1

So I'm working on my login system, using Mongo for my backend. I want to be able to have multiple users on one account so I'm developing a route to deal with this. I have a model for my accounts and a schema for my users. This is how I am trying to create a user currently:

router.post('/CreateUser', async(req, res) =>{
    try{

        const acc = await Account.findOne({"Email": req.body.Email});
        if(!acc) throw Error('Email not found');
        var newUser = new User(req.body.User); 
        acc.Users.push(newUser);
        res.status(200).send({success:true});

    }
    catch(err){
        res.status(400).send({msg:err.toString(),success:false});

    }
});

Here is my UserSchema:

const UserSchema = new Schema({
    // Name of the user
    Username:{
        type:String,
        required:true,
        unique:true
    },
    // PIN for each user
    PIN:{
        type:Number,
        require:true
    }

});

module.exports = UserSchema;

My Account Model:

const User = require('../Models/UserData');

const AccountSchema = new Schema({
    // Email linked to this account
    Email:{
        type:String,
        unique:true,
        required:true,
        index:true
    },
    // Password for the account
    Password:{
        type : String,
        required : true
    },
    // Users on this account
    Users:{
        type:[User],
        required:true
    }
});

module.exports = mongoose.model('Account', AccountSchema);

It returns success:true, but the only change I see in the database is an entirely new collection that is completely empty. I also need to check if the username already exists, but one step at a time.

Edit: This is body that I'm using for the POST request:

{
    "Email":"Paul@test.com",
    "User":
    {
        "Username":"56",
        "PIN":4659
    }
}
FallingInForward
  • 285
  • 2
  • 4
  • 12

1 Answers1

0

Save the updated record to DB acc.save if you want to save record to user model as well call user.save

router.post('/CreateUser', async(req, res) =>{
    try{

        const acc = await Account.findOne({"Email": req.body.Email});
        if(!acc) throw Error('Email not found');
        var newUser = new User(req.body.User);
        acc.Users.push(newUser);
        const saveAccount = await acc.save(); // SAVE Account
        const saveUser = await newUser.save(); // SAVE User


    }
    catch(err){
        res.status(400).send({msg:err.toString(),success:false});

    }
});
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107