Unable to store Object Id from one schema to another in MongoDb using mongoose

276 views
Skip to first unread message

piyush kuhad

unread,
Oct 12, 2020, 9:07:12 AM10/12/20
to Mongoose Node.JS ODM
I have asked the same question on Stack Overflow: Please follow this link for better code visuals: 

I am building a Budget Manager App.

It has BudgetSchema which contains 2 other schemas: revenueSchema and expenseSchema (both have similar structure).

Here's Budget Schema:

//BUDGET MODEL
const revenueSchema = new mongoose.Schema({
  categoryId: {
    type: mongoose.Schema.ObjectId,
    ref: 'Revenue',
  },
  categoryAmount: {
    type: Number,
    required: [true, 'Revenue must have an amount'],
    min: [0, 'Amount cannot be less than 0'],
  },
  transactionType: {
    type: String,
    default: 'revenue',
  },
  added: Boolean,
});

const expenseSchema; //this is same as revenueSchema

const budgetSchema = new mongoose.Schema({
  budgetName: {
    type: String,
    trim: true,
    maxlength: [40, 'Budget name must not be more than 40 characters'],
  },
  budgetStartDate: {
    type: Date,
    required: [true, 'Budget must have a start date'],
  },
  budgetEndDate: {
    type: Date,
    required: [true, 'Budget must have an end date'],
  },
  revenueData: { type: [revenueSchema] },
  expenseData: { type: [expenseSchema] },
  createdAt: {
    type: Date,
    default: Date.now(),
  },
});

const Budget = mongoose.model('Budget', budgetSchema);


In revenueSchema, property CategoryId is referencing to ObjectId of 'Revenue' model, whose schema is: 

//REVENUE MODEL
const revenueSchema = new mongoose.Schema({
  categoryName: {
    type: String,
    trim: true,
    maxlength: [40, 'Revenue name must not be more than 40 characters'],
  },
  categoryValue: { //sluggified version of categoryName
    type: String,
  },
  defaultCategory: {
    type: Boolean,
    default: false,
  },
  added: Boolean,
}); 


Revenue model contains all the Revenue Categories (Salary, Pensions etc)

When a Budget is created based on BudgetSchema. I am getting revenueCategories in request and if any of the revenueCategories exists in Revenue Collection(based on Revenue Model), I want to save it's _id reference in categoryId property of revenueSchema in Budget Model.

Here's the Code have written: (Controller.js)

exports.createBudget = async (req, res) => {
  /*
   Structure of revenueCategories Array from req.body
   [{
         "categoryName":"Salary",
         "categoryAmount":"35000",
         "type":"revenue",
         "categoryValue":"salary",
         "added":true
      }, {
         "categoryName":"Other Source",
         "categoryAmount":"2000",
         "type":"revenue",
         "categoryValue":"other-source",
         "added":true
      }]
  */

  const revenueData = await req.body.revenueCategories.map(async (el) => {
    //Check if Revenue exists in Revenue Model's Collection, if true get it's _id
    let currentDoc = await Revenue.findOne({
      categoryValue: el.categoryValue,
    }).select('_id');

    //if we have _id then assign it to categoryId property
    if (currentDoc !== null) {
      el.categoryId = await currentDoc._id;
    } 

    //if new Revenue Category then create new Doc and assign it's _id to categoryId property
    else if (currentDoc === null) {
      let newCategData = {
        categoryName: el.categoryName,
        categoryValue: el.categoryValue,
      };

      let newCateg = await Revenue.create(newCategData);
      el.categoryId = await newCateg._id;
    }

    console.log(el); //show el object with correct categoryId

    return el;
  });

  console.log('Revenue Data', revenueData); //***this gives array of pending promises***

  const budgetDoc = {
    ...req.body.budgetData,
    revenueData, //first testing with revenue, then will do the same with expense below
    expenseData: req.body.expenseCategories,
  };

  const budget = await Budget.create(budgetDoc);

  res.status(201).json({
    data: {
      status: 'success',
      budget,
    },
  });
};

PROBLEM

When I try to console.log the revenueData i am getting an array of pending promises which is resulting in an validation error by mongoDb while creating new Budget document.

How can solve this issue?

Reply all
Reply to author
Forward
0 new messages