[英]create Schema and retrieve mongoose nested objects array values
Actually my aim is to find the total time spent in each category for example in solution 实际上,我的目的是找到每个类别的总时间,例如解决方案中的时间
or Billing category, please provide me a solution, I am new to mongoose so I 或“结算”类别,请为我提供解决方案,我是猫鼬的新手,所以我
don't know the correct way to achieve this (is it possible to use MapandReduce method?). 不知道实现此目标的正确方法(是否可以使用MapandReduce方法?)。
Thanks in Advance. 提前致谢。
userSchema = mongoose.Schema({
username: {
type: String,
required: true
},
type: String,
timesheet: {
created: {
type: Date
},
categories: [{
catname: String,
cusname: String,
hours: Number
}]
}
});
var User = mongoose.model('User', userSchema);
module.exports = function (app) {
var usr = {
username: "Ardrew",
type: "Billing",
timesheet: {
created: new Date('2014-06-04'),
categories: [{
catname: "Solution",
cusname: "IBM",
hours: 8
}, {
catname: "Solution",
cusname: "AT&T",
hours: 4
}, {
catname: "Sales",
cusname: "AT&T",
hours: 4
}]
}
}
var user = new User(usr);
user.save(function (err, user) {
});
/* User.find({"timesheet.categories.catname":"Solution"},function(err,result){
console.log(result)
}*/
Model.find
queries the collection for documents that match the criteria provided in the first argument. Model.find
在集合中查询与第一个参数中提供的条件匹配的文档。 For example: 例如:
User.find({type: 'Sales'}, function (err, docs) { })
This example query will find all the documents where type
is Sales
. 此示例查询将查找
type
为Sales
所有文档。 The callback receives a cursor that you can iterate. 回调接收一个可以迭代的游标。
But in your case it's not even needed to call find
. 但是在您的情况下,甚至不需要调用
find
。 Model#save
returns the document in the callback, so you can access the field like this: Model#save
在回调中返回文档,因此您可以像这样访问字段:
user.save(function(err, user) {
console.log(user.timesheet.categories);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.