简体   繁体   中英

Create array of array Schema using mongoose for NodeJS

I want to create a DB Schema to store the data as below

{
    name : "xyz",
    admin : "admin",
    expense : [ 
                jan: [{expenseObject},{expenseObject}], 
                feb: [[{expenseObject},{expenseObject}]
              ]
}

Expense Object

var expenseSchema = new Schema({
    particular : String,
    date : {type : Date, default: Date.now},
    paid_by : String,
    amount : Number
});

Can someone help me create a schema for the same.

Any suggestions for a better Schema for the same concept are welcome.

You can use Sub Docs

var parentSchema = new Schema({
  name: { type: String },
  admin: { type: String },
  expense: [expenseSchema]
});

Or, if you need the expenseObjects to be stored in a seperate collection you can use refs , where Expense would be the name of another model

var parentSchema = new Schema({
  name: { type: String },
  admin: { type: String },
  expense: [{ type: Schema.Types.ObjectId, ref: 'Expense' }],
});
var expenseSchema = new Schema({
  particular : String,
  date : {type : Date, default: Date.now},
  paid_by : String,
  amount : Number
});

// your schema
var mySchema = new Schema({
   name : {type: String, trim: true},
   admin : {type: String, trim: true},
   expense: [expenseSchema]
});

--- UPDATE:

With this update now expense is an array of expenseSchema without any categorisation of month. Then if you want to get all expenses in a particular month you can simply do an aggregation like this:

db.users.aggregate(
  [
   // this match is for search the user
   { $match: { name: "<ADMIN NAME>"} },
   // this unwind all expenses of the user selected before
   { $unwind: "$expense" },
   // this project the month number with the expense
   {
     $project: {
      expense: 1, 
      month: {$month: '$expense.date'}
    }
   },
   // this search all the expenses in a particular month (of the user selected before)
   { $match: { month: 8 } },
   // this is optional, it's for group the result by _id of the user
   //(es {_id:.., expenses: [{}, {}, ...]}. Otherwise the result is a list of expense
   {
    $group: {
      _id:"$month",
      expenses: { $addToSet: "$expense"}
    }
  }
 ]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM