[英]Create array of array Schema using mongoose for NodeJS
I want to create a DB Schema to store the data as below 我想创建一个DB Schema来存储数据,如下所示
{
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. 欢迎任何有关同一概念的更好Schema的建议。
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 或者,如果您需要将expenseObjects存储在单独的集合中,您可以使用refs ,其中Expense将是另一个模型的名称
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. 现在,此更新expense
是一个expenseSchema
数组,没有任何月份分类。 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"}
}
}
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.