Reputation: 618
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.
Upvotes: 2
Views: 50
Reputation: 48476
According the document saved in the db
{ "_id" : ObjectId("56f8dc3de430d672036bf325"), "meta" : { "book" : "architecture design", "company" : "cloud consulting" }, "birthday" : ISODate("1970-06-09T16:00:00Z"), "address" : { "_id" : ObjectId("56f8dc3de430d672036bf326"), "zipcode" : 135090, "city" : "youngin", "state" : "Kyungki" }, "name" : "terry", "image" : { "data" : "test is here...", "contentsType" : "image/png" }, "__v" : 0 }
We can get the difference among them,
address : addressSchema,
which is sort of sub-doc, one additional _id
could be found in address
field, "address" : { "_id" : ObjectId("56f8dc3de430d672036bf326"), "zipcode" : 135090, "city" : "youngin", "state" : "Kyungki" }
image : {data : Buffer, contentsType : String}
is pure nested document, there are only defined fields in image
.
meta : mongoose.Schema.Types.Mixed
, you can define an "anything goes" SchemaType, its flexibility comes at a trade-off of it being harder to maintain. refer to doc.
Upvotes: 1