Reputation: 43
Thanks for your help and valuable time. As you suggested I have created the schema's as below. Now I want to get records based on customer name to calculate the hours spent by them on each category. Please help me out in this. Thanks in Advance.
/*var query = {'timesheets[0].categories[0].catname':"Admin"} // I want to get all the records or documents with category admin */
Timesheet = new Schema({
created: {type: Date, default: Date.now},
categories: [{
catname: String,
custname: String,
hours: Number
}]
});
User = new Schema({
name: { type: String, required: true },
email:String,
password:String,
type:String,
timesheets: [Timesheet]
});
//timesheets: [{type: mongoose.Schema.Types.ObjectId, ref: 'Timesheet'}
var User = mongoose.model("User",User);
var Timesheet = mongoose.model("Timesheet",Timesheet);
module.exports = function(app) {
var timedata = {
created: new Date('2014-06-05'),
categories:[{catname:"Admin",cusname:"Sony",hours:8}]
}
var user = new User({
name:"Nelson",
email:"[email protected]",
password:"welcome123",
type:"Solutions"
});
var timesheet = new Timesheet(timedata);
user.timesheets.push(timesheet);
user.save(function(err,user){
console.log(user.timesheets.timesheet);
})
//console.log('category name');
//console.log(user.timesheets[0].categories[0].catname)
var query = {'timesheets[0].categories[0].catname':"Admin"}
// I want to get
all the records or documents with category admin
User.find(query,function(err,catname){
console.log('catname')
console.log(catname)
})
Upvotes: 0
Views: 204
Reputation: 2512
To create a child schema you should first define it and then insert into your primary schema. Alternatively, if you anticipate a lot of timesheets it's probably preferable to reference an independent schema. In both cases it would make sense to attach these to a User schema:
var Timesheet = new Schema({
created: {type: Date, default: Date.now},
categories: [{
name: String,
custname: String,
hours: Number
}]
});
Using embedded documents:
var User = new Schema({
timesheets: [Timesheet]
});
Insert can then be done directly using:
// create new timesheet doc using your user doc
var timesheet = user.timesheets.create(myData);
user.timesheets.push(timesheet);
or simply:
user.timesheets.push(data);
Using referenced documents:
var User = new Schema({
timesheets: [{type: Schema.Types.ObjectID, ref: 'Timesheet'}]
});
insert with:
// push timesheet reference to your user doc
var timesheet = new Timesheet(data);
user.timesheets.push(timesheet._id);
Upvotes: 1