node.js - Nested schema in Mongoose -


thanks , valuable time. suggested have created schema's below. want records based on customer name calculate hours spent them on each category. please me out in this. in advance.

/*var query = {'timesheets[0].categories[0].catname':"admin"} // want records or documents 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:"nelson@gmail.com",           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"}         // want           records or documents category admin                user.find(query,function(err,catname){             console.log('catname')             console.log(catname)          }) 

to create child schema should first define , insert primary schema. alternatively, if anticipate lot of timesheets it's preferable reference independent schema. in both cases make sense attach these 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 done directly using:

// create new timesheet doc using 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 user doc var timesheet = new timesheet(data); user.timesheets.push(timesheet._id); 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -