Search code examples
node.jsmongodbmongoosemongoose-schema

How to add data inside nested array in mongodb


I am using mongoose for database functionalities in my nodejs project.Below is my model.

Here is the POST request:

enter image description here

In MongoDb data is saving like this :

enter image description here

Here owers array is empty. expense.js

const mongoose = require('mongoose');

const ExpenseSchema = new mongoose.Schema({

  userid:{
      type: String,
      required: true
  },
  owers:[{
     owerid:{
        type: String
      },
     amt:{
       type: Number  
     }
    }],
  name:{
    type: String,
    required: true
  },
  amount:{
      type: Number,
      require: true
  }
});

const expense = mongoose.model('expense',ExpenseSchema);
module.exports = expense;

Whenever I am trying to insert something array is showing empty.Below is my code:

addExpense.js

const expense = require('../models/expense.js');

const addExpense = async (req,res) => {

const {name,amount,owerid,amt} = req.body;
console.log(name + " " + owerid);
const {userid} = req.params;

const expens = new expense({userid,name,amount});

try{
    const data = await expens.save();
    expens.owers.push({"owerid":owerid,"amt":amt});
    res.send({"id":data._id}); 
}
catch(error){
    res.send(error);
}
};

module.exports = {addExpense};

Someone let me know what I am doing wrong.


Solution

  • Enter owers value like that

    Try This
       const {name,amount,owers} = req.body;
            console.log(name + " " + owerid);
            const {userid} = req.params;
            
            const expens = new expense({userid,name,amount});
            
            try{
                const data = await expens.save();
            
               //After you can push multiple data like that
            
              JSON.parse(owers).map((value) => {
                data.owers.push({
                    owerid: value.owerid,
                    amt: value.amt
                })
            })
            
               data.save()
            
                res.send({"id":data._id}); 
            }
            catch(error){
                res.send(error);
            }