During investigating mongoose nested document, i found that it has number of ways.
/*
Collection : profiles
{
"name":"terry",
"address":{
"zipcode":135090,
"city":"seoul",
"state":"kyungki"
},
"birthday":"1975-03-03",
"meta":{
"company":"cloud consulting",
"book":"architecture design"
},
"image":{
"data":"xxxxxxx",
"contentType":"image/png"
}
}
*/
var mongoose = require('mongoose');
var fs = require('fs');
mongoose.connect('mongodb://localhost:27017/mydb');
var addressSchema = new mongoose.Schema({
zipcode : Number,
city : String,
state : String
});
var profileSchema = new mongoose.Schema({
name : String,
address : addressSchema,
birthday : Date,
meta : mongoose.Schema.Types.Mixed,
image : {
data : Buffer,
contentsType : String
}
});
var Profile = mongoose.model('profiles',profileSchema);
var Address = mongoose.model('address',addressSchema);
var p = new Profile();
p.name = "terry";
// address
var a = new Address();
a.zipcode = 135090;
a.city = "youngin";
a.state = "Kyungki";
p.address = a;
// birthday
p.birthday = new Date(1970,05,10);
// meta
p.meta = { company : 'cloud consulting', book : 'architecture design'};
// image
p.image.contentsType='image/png';
var buffer = fs.readFileSync('/Users/terry/nick.jpeg');
p.image.data = buffer;
p.save(function(err,silece){
if(err){
cosole.log(err);
return;
}
console.log(p);
});
as you can see, address, meta and image fields are nested document. For address field i created addressSchema field and meta field i used Mixed type in mongoose. and for the image field i just defined the nested document in the ProfileSchema.
I used 3 different ways, but i dont know what is difference between them.
Could u plz kindly give me a hint for this? Thanx in advance.