您的位置:首页 > 编程语言 > Go语言

use mongoose to update documents with model and Schema

2014-01-17 09:20 381 查看
Problem

定义Schema 和Model,在Schema定义了嵌套的数据结构,例如:

然后获取model

var Adapter = new Schema({entity: []})

那么将来更新了 adapter,并使用 Model进行save或update时,entities一直没变化。

就是说,没有办法更新数据库记录。

Solution

So.1
http://stackoverflow.com/questions/8242601/node-mongoose-problems-saving-multiple-depths-of-nested-schema
如果是定义多层的数据,嵌套。

那么就需要声明多个schema

例如

var Entity = new Schema({
foo:String,
bar:String
})
var Adapter = new Schema({
entity: [Entity]
})


So.2
http://mongoosejs.com/docs/schematypes.html
use mixed type 

var schema = new Schema({
name:    String,
binary:  Buffer,
living:  Boolean,
updated: { type: Date, default: Date.now }
age:     { type: Number, min: 18, max: 65 }
mixed:   Schema.Types.Mixed,
_someId: Schema.Types.ObjectId,
array:      [],
ofString:   [String],
ofNumber:   [Number],
ofDates:    [Date],
ofBuffer:   [Buffer],
ofBoolean:  [Boolean],
ofMixed:    [Schema.Types.Mixed],
ofObjectId: [Schema.Types.ObjectId],
nested: {
stuff: { type: String, lowercase: true, trim: true }
}
})

// example use

var Thing = mongoose.model('Thing', schema);

var m = new Thing;
m.name = 'Statue of Liberty'
m.age = 125;
m.updated = new Date;
m.binary = new Buffer(0);
m.living = false;
m.mixed = {[ any: { thing: 'i want' } ]};
m.markModified('mixed');
m._someId = new mongoose.Types.ObjectId;
m.array.push(1);
m.ofString.push("strings!");
m.ofNumber.unshift(1,2,3,4);
m.ofDate.addToSet(new Date);
m.ofBuffer.pop();
m.ofMixed = [1, [], 'three', { four: 5 }];
m.nested.stuff = 'good';
m.save(callback);


Get it done



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐