如何使用mongoose将动态字段添加到现有集合

时间:2014-07-01 18:53:19

标签: node.js mongodb mongoose

我正在尝试创建一个名为产品的mongodb集合,其中我有字段(id,名称,价格和属性),现在不同的产品具有不同类型的属性,例如iphone与nike shoes相比具有不同的属性集。那么如何定义一个模式并使用mongoose动态添加新的键和值对。

{
  "_id":"001",
  "name":"iphone 5",
  "price":$650,
  "properties":{
    'weight':2.3, 
    'talktime': '8 hours', 
    'battery type': 'lithium'
  }
}


{
  "_id":"002",
  "name":"nike shoes",
  "price":$80,
  "properties":{
    'size':10, 
    'color':black
  }
}

1 个答案:

答案 0 :(得分:7)

看一下Mongoose的混合模式类型:http://mongoosejs.com/docs/schematypes.html。如果为属性({})指定该类型,则允许将任何内容保存到该属性中。

例如:

var ProductSchema = new Schema({
    name: String,
    price: String,
    properties: {}
});
mongoose.model("Product", ProductSchema);


var Product = mongoose.model("Product");
var product = new Product({
    "name": "iphone 5",
    "price": "$650",
    "properties": {
        "weight": 2.3,
        "talktime": "8 hours",
        "battery type": "lithium"
    }
});
product.save();

运行上面的代码后,数据库现在包含此文档:

{
    "name" : "iphone 5",
    "price" : "$650",
    "properties" : {
        "battery type" : "lithium",
        "talktime" : "8 hours",
        "weight" : 2.3
    },
    "_id" : ObjectId("53b35ca575e9d7a40de0edb7"),
    "__v" : 0
}