mogoose中嵌套文档的区别是什么?

时间:2016-03-28 05:59:30

标签: node.js mongodb mongoose mongoose-schema

在调查mongoose嵌套文档时,我发现它有多种方式。

/*
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字段和meta字段,我在mongoose中使用了Mixed type。对于图像字段,我刚刚在ProfileSchema中定义了嵌套文档。

我使用了3种不同的方式,但我不知道它们之间有什么区别。

你能不能给我一个暗示? Thanx提前。

1 个答案:

答案 0 :(得分:1)

根据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" } LI>
  • image : {data : Buffer, contentsType : String}是纯粹的嵌套文档,image中只有已定义的字段。

  • meta : mongoose.Schema.Types.Mixed,你可以定义一个"任何事情都可以" SchemaType,它的灵活性来自于它难以维护的权衡。请参阅doc