Home > Mobile >  How do I add expenses for only specific users?
How do I add expenses for only specific users?

Time:11-15

I have created two models in my app- one for User (_id, email, username, password) and one for Expense (_id, date, detail, amount, category). For the users, I have finished the authentication with jwt. I want logged-in users to be able to add/remove expenses and not show their expenses to other users but I don't know how I can implement that. I am not asking for code- I would be grateful if you could roughly tell me what I need to do. Thanks!

//expense schema
const expenseSchema = new mongoose.Schema(
    {
        date: Date,
        detail: String,
        amount: Number,
        category: String
    }
)
//controller for adding expenses
const addExpenseController =     (req, res) => {
    const expense = new Expense({
        "date": new Date(),
        "amount": req.body.amount,
        "detail": req.body.detail,
        "category": "expense"
    });
    expense.save();

    res.send('expense added');
};

CodePudding user response:

You should define a ref property in the expense schema pointing at the User model (change the value of the ref attribute to equal the model name given to the users):

const expenseSchema = new mongoose.Schema(
  {
      ...
      user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
      }
  }
)

Then, on creation, specify the user by setting the value of its _id.
You can either store it in the session or pass it in the body, depending on your implementation:

const addExpenseController =     (req, res) => {
  const expense = new Expense({
      date: new Date(),
      amount: req.body.amount,
      detail: req.body.detail,
      category: "expense",
      user: req.session.user_id // or req.body.user_id
  });
  expense.save();

  res.send('expense added');
};
  • Related