node.js - How to define a single reference schema using mongoose -


i new in node.js , mongodb , in below code define reference in table employee of department here when insert or data employee table in array format want define reference single column not multiple.

var employee = new mongoose.schema({     name: string,     dept: [department] });  var department = new mongoose.schema({      dept_name : string,      dept_code : string }) 

i want data in response employee table in format `{"name":"cs",dept:{"id":_id_of_dept}}

please guide me correct way achieve objective.

you can nest using references or arrays, in example, can either create department record , reference in employee document, or have array of departments employee (which understand not want do).

to reference department document employee use like:

var department = new mongoose.schema({     dept_name : string,     dept_code : string });  mongoose.model('department', department);  var employee = new mongoose.schema({     name: string,     dept: { type: schema.types.objectid, ref: 'department' } }); 

however, you'll need populate when querying employee gather department data.

but @ high level, looking @ you're trying accomplish, i'd suggest directly storing department within employee document. relational databases may end patterns you've described above, in document based databases, there's not reason separate out department employee. doing i've put below in future queries , general access of data:

var employee = new mongoose.schema({     name: string,     dept: {         dept_name : string,         dept_code : string     } }); 

this answer might helpful in understanding mean.


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 -