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]
});
的名字
---更新:
現在這個更新expense
是沒有任何月份分類的expenseSchema
的數組。然後,如果你想獲得的所有費用在特定的月份,你可以簡單地做一個像這樣的聚合:
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"}
}
}
]);
我可以添加一月,二月,等通過代碼,而不是架構硬編碼呢?就像我的意思是說只有在需要時才添加月份數組 –
nope。使用此解決方案,您只能硬編碼所有月份。您無法定義將來動態更改的模型(例如添加一個月)。你可以改變你的結構或硬編碼整個月,如果沒有花費的陣列它是空的。檢查[this](https://github.com/Automattic/mongoose/issues/1867) – gianlucatursi
有沒有更好的方法來做到這一點?我需要爲此文檔存儲每個月的費用。而費用是問題中提到的一個對象。如果你能提供一些更好的想法,那會很好。 –