Mongoose -- Schemas Models Documents
来源:互联网 发布:云计算解决方案 编辑:程序博客网 时间:2024/06/02 06:11
Schemas
Mongoose中,所有的东西都由Schemas开始。schema相当于是MongoDB的collection,并且定义了文档的结构。
var mongoose = require('mongoose');var Schema = mongoose.Schema;var blogSchema = new Schema({ title: String, author: String, body: String, comments: [{ body: String, date: Date }], date: { type: Date, default: Date.now }, hidden: Boolean, meta: { votes: Number, favs: Number }});
上面的例子中,属性名后面是属性的类型,Schema允许的类型包括:
StringNumberDateBufferBooleanMixedObjectIdArray
schema不仅可以用来定义文档的结构和属性,而且还可以用来定义实例方法,静态方法,索引,生命周期钩子方法,这些将在下文详细说明。
接下来,我们需要使用Schema来生成一个Model。
var Blog = mongoose.model('Blog', blogSchema);
实例方法
关键字:Schema.methods
实例方法可以使用Schema来定义。
// define a schemavar animalSchema = new Schema({ name: String, type: String });// assign a function to the "methods" object of our animalSchemaanimalSchema.methods.findSimilarTypes = function(cb) { return this.model('Animal').find({ type: this.type }, cb);};
如此,所有的Animal实例都将拥有findSimilarTypes方法。
var Animal = mongoose.model('Animal', animalSchema);var dog = new Animal({ type: 'dog' });dog.findSimilarTypes(function(err, dogs) { console.log(dogs); // woof});
Model静态方法
关键字:Schema.statics
animalSchema.statics.findByName = function(name, cb) { return this.find({ name: new RegExp(name, 'i') }, cb);};var Animal = mongoose.model('Animal', animalSchema);Animal.findByName('fido', function(err, animals) { console.log(animals);});
索引
不太懂…附上原文吧。
虚拟属性
虚拟属性允许我们创建一个在MongoDB中不存在的属性。
personSchema.virtual('fullName').get(function () { return this.name.first + ' ' + this.name.last;});
这样,我们就可以访问实例的fullName属性了,但其实这个属性在数据库中并不存在。
同时,给fullName我们还可以设置set:
personSchema.virtual('fullName'). get(function() { return this.name.first + ' ' + this.name.last; }). set(function(v) { this.name.first = v.substr(0, v.indexOf(' ')); this.name.last = v.substr(v.indexOf(' ') + 1); });axl.fullName = 'William Rose'; // Now `axl.name.first` is "William"
这样,当我们设置fullName时,first name和last name也将会被设置。
Options
当我们新建一个Schema的时候,第一个参数可以规定Schema的数据结构(key: type),第二个参数可以定义可选options;如果定义的时候省略第二个参数,则可以使用set方法。
代码如下:
new Schema({..}, options);// orvar schema = new Schema({..});schema.set(option, value);
可以选择的options包括:
autoIndexcappedcollectionemitIndexErrorsid_idminimizereadsafeshardKeystricttoJSONtoObjecttypeKeyvalidateBeforeSaveversionKeyskipVersioningtimestampsretainKeyOrder
详情可见:
http://mongoosejs.com/docs/guide.html#autoIndex
Models
var schema = new mongoose.Schema({ name: 'string', size: 'string' });var Tank = mongoose.model('Tank', schema);
新建文档
文档就是Model的实例,有两种方式可以将数据保存到数据库。
var Tank = mongoose.model('Tank', yourSchema);var small = new Tank({ size: 'small' });small.save(function (err) { if (err) return handleError(err); // saved!})// orTank.create({ size: 'small' }, function (err, small) { if (err) return handleError(err); // saved!})
注意:如果不建立mongoose的连接,数据是无法保存的。每个Model都有一个绑定的连接。当开发者调用方法mongoose.model()的时候,这个Model将会使用默认的mongoose连接。
mongoose.connect('localhost', 'gettingstarted');
如果你建立了一个常用的连接,可以用这个连接来创建model:
var connection = mongoose.createConnection('mongodb://localhost:27017/test');var Tank = connection.model('Tank', yourSchema);
查询
查询方法包括: find, findById, findOne, where。
Tank.find({ size: 'small' }).where('createdDate').gt(oneYearAgo).exec(callback);
具体将在后文介绍。
删除
Tank.remove({ size: 'large' }, function (err) { if (err) return handleError(err); // removed!});
更新
更新方法:findOneAndUpdate
Documents
更新方法
Tank.findById(id, function (err, tank) { if (err) return handleError(err); tank.size = 'large'; // or tank.set({ size: 'large' }); tank.save(function (err, updatedTank) { if (err) return handleError(err); res.send(updatedTank); });});
上面这个方法,会返回这个查找到的tank实例,如果我们不需要查找功能,只需要更新,则可以使用下面这个方法:
Tank.update({ _id: id }, { $set: { size: 'large' }}, callback);
如果我们需要返回实例,下面这个方法也是一个很好的选择:
Tank.findByIdAndUpdate(id, { $set: { size: 'large' }}, { new: true }, function (err, tank) { if (err) return handleError(err); res.send(tank);});
- Mongoose -- Schemas Models Documents
- Generating XML Documents from XML Schemas
- How to validate Xml Documents against schemas in BizTalk
- use mongoose to update documents with model and Schema
- Documents
- .Documents
- mongoose
- mongoose
- Mongoose
- Mongoose
- mongoose
- mongoose
- mongoose
- Mongoose
- mongoose
- Mongoose
- mongoose
- mongoose
- 909422229_JavaWeb之Servlet原生文件下载
- AngularJS杂记7----过滤器filter案例详解
- composer安装
- 记一次SQL Server的清理过程
- 欢迎使用CSDN-markdown编辑器
- Mongoose -- Schemas Models Documents
- JavaEE 6及以上版本的web.xml问题?
- HDU
- 【CVTE】请使用js编写一个函数:chunk(arr,size),把一个数组arr按照指定的数组大小size分割成若干个数组块,传入的参数分别为数组
- Tex Studio配置字典用于检查拼写
- 旨在物联网领域拔得头筹,LoRa成为运营商重要武器
- Apache Kafka
- 150. Evaluate Reverse Polish Notation
- vs2010 无法将 复制到 超出了重试计数10