Whenever a user register to my app, create a default budget for him

Hello everyone. I’m currently learning Express and MongoDB using Mongoose in my apps.

My question is:

  • imagine a new user registers to the app and a default budget should be added to his account.
    the default budget document should be inserted into the Budget collection
    is there a built-in function on Mongoose doing the job, or should I add it manually?

Thanks

Hello :wave: @Oussama_Louelkadi,

Welcome to the MongoDB Community forums :sparkles:

There is one scenario where you can store the budget in the same collection as the user, and that is when you can use the Mongoose Defaults option. Your schemas can define default values for certain fields. If you create a new document without setting that path, the default value will be used.

For example, if your schema looks like this:

const userSchema = new mongoose.Schema({
  name: String,
  email: String,
  password: String,
  // other user properties
  budget:  { type: Number, default: 1000 } //For example, consider 1000
});

In this case, budget is one of the fields in userSchema, so you can use the default value.

However, as you mentioned in your post:

If you want to insert a value in a different collection that will be used after the registration process, you can achieve this by writing your own code in your registration route. Unfortunately, there is no built-in function in Mongoose that specifically handles this case.

Sharing the sample code snippet for your reference:

app.post('/register', async (req, res) => {
  // create new user
  const newUser = new User({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password
    ...
  });

  // save new user to database
  await newUser.save();

  // create default budget for new user
  const newBudget = new Budget({
    userId: newUser._id,
    amount: 1000 // set default budget amount here
    ...
  });

  // save new budget to database
  await newBudget.save();

Please note that this is the sample snippet and it is recommended that you thoroughly test the code in a testing environment to ensure it meets all of your use cases and requirements before implementing it in production.

I hope it helps. Let us know if you have any further queries.

Best,
Kushagra

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.