一、npm
安装Mongoose
$ npm install mongoose
连接我们本地的 test
数据库
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
connect()
返回一个状态待定(pending)的连接, 接着我们加上成功提醒和失败警告
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
// we're connected!
});
连接成功时,回调函数会被调用。简洁起见, 我们假设下面所有函数都运行在这个回调函数里。
Mongoose 里,一切都始于Schema。 现在我们来看一个例子:
var kittySchema = mongoose.Schema({
name: String
});
很好,我们得到了一个带有 String
类型 name
属性的 schema 。 接着我们需要把这个 schema 编译成一个 Model:
var Kitten = mongoose.model('Kitten', kittySchema);
model 是我们构造 document 的 Class
var felyne = new Kitten({ name: 'Felyne' });
console.log(felyne.name); // 'Felyne'
二、创建表与MongoDB连接
Schema() :创建Tables
Parameters
- definition «Object»
- [options] «Object»
Schema 构造函数。
示例:
var child = new Schema({ name: String });
var schema = new Schema({ name: String, age: Number, children: [child] });
var Tree = mongoose.model('Tree', schema);
// 设置 schema 选项参数
new Schema({ name: String }, { _id: false, autoIndex: false })
Options:
- autoIndex: bool - 缺省值 null (即使用数据库连接自带的 autoIndex 选项)
- bufferCommands: bool - 缺省值 true
- capped: bool - 缺省值 false
- collection: string - 没有缺省值
- id: bool - 缺省值 true
- _id: bool - 缺省值 true
minimize
: bool - 当 document#toObject 被手动调用时控制其行为 - 缺省值 true- read: string
- safe: bool - 缺省值 true.
- shardKey: bool - 缺省值
null
- strict: bool - 缺省值 true