在研究猫鼬嵌套文档时,我发现它有多种方法。
/*
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);
});
如您所见,地址,元和图像字段是嵌套文档。对于地址字段,我创建了addressSchema字段和元字段,在猫鼬中使用了混合类型。对于图像字段,我只是在ProfileSchema中定义了嵌套文档。
我使用了3种不同的方式,但是我不知道它们之间的区别是什么。
请您给我一个提示吗?提前感谢。
最佳答案
根据文件保存在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 }
我们可以得到他们之间的区别,
address : addressSchema,
属于sub-doc,在_id
字段address
中可以找到一个附加的"address" : { "_id" : ObjectId("56f8dc3de430d672036bf326"), "zipcode" : 135090, "city" : "youngin", "state" : "Kyungki" }
image : {data : Buffer, contentsType : String}
是纯嵌套文档,在image
中只有定义的字段。meta : mongoose.Schema.Types.Mixed
,您可以定义一个“万事俱备”的SchemaType,它的灵活性来自于难以维护的折衷。请参阅doc。关于node.js - Mongoose 中嵌套文档的区别类型是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36256820/