Mongoose 的几个重要的概念:
(1)连接(2)模型Schema(3)索引(4)分页(5)转换(6)中间件(7)自动产生键
通用操作:
var mongoose = require('mongoose')//获取mongoose模块
var Schema = mongoose.Schema;//获取Schema模块
//创建模型,这个模型指出了数据库中集合的字段类型
var CharacterSchema = Schema({
name: { type: String, required: true }
, health: { type: Number, min: 0, max: 100 }
})
有了模型必须要把模型添加到mongoose的模型中:
var Character = mongoose.model('Character', CharacterSchema);
这个方法有是三个参数,第一个是获取模型的名称,第二个是Schema的对象,第三个是数据库中集合名称,如果不指定第三个参数,那么数据库中集合的名称就使用第一个参数的附属形式。
在mongoose中操作数据库都是通过模型,来操作的。
(一)首先介绍保存的方法:
create:方法
Character.create({ name: 'Link', health: 100 }, function (err, link) {
if (err) return done(err);
console.log('found', link);
link.attack(); // 'Link is attacking'
mongoose.disconnect();
// done();
})
save方法
new Character({ name: 'Link', health: 100 }).save( function (err, link) {
if (err) return done(err);
console.log('found', link);
mongoose.disconnect();
});
给Schema 添加自定义方法:
CharacterSchema.methods.show = function () {
console.log('%s is attacking', this.name);
}
这个方法写在var Character = mongoose.model('Character', CharacterSchema,'Character');的前面。
(二)Schema
var CharacterSchema = Schema({
name: { type: String, required: true }
, health: { type: Number, min: 0, max: 100 }
})
这个也可以这么写:
var CharacterSchema = Schema({
name:String
, health: Number
})
字段类型:
{ type: String, required: true }字符串类型,必须
{ type: String, index: true } 字符串类型,索引
Date 日期类型
如果有多级目录,那么可以在comments中
var Comment = new Schema();
Comment.add({
title : { type: String, index: true }
, date : Date
, body : String
, comments : [Comment]
});
var Comment = new Schema();
Comment.add({
title : { type: String, index: true }
, date : Date
, body : String
, comments : [Comment]
});
var BlogPost = new Schema({
title : { type: String, index: true }//主键索引
, slug : { type: String, lowercase: true, trim: true }//大写
, date : Date //日期
, buf : Buffer //图片
, comments : [Comment]
, creator : Schema.ObjectId //ID
});
var Comment = new Schema();
Comment.add({
title : { type: String, index: true }
, date : Date
, body : String
, comments : [Comment]
});
{ type: String, required: true, index: { unique: true, sparse: true } }
var Comment = new Schema();
Comment.add({
title : { type: String, index: true }
, date : Date
, body : String
, comments : [Comment]
});
这是查询:
// when querying data, instead of providing a callback, you can instead
// leave that off and get a query object returned
var query = Person.find({ age : { $lt : 1000 }});
// this allows you to continue applying modifiers to it
query.sort('birthday');
query.select('name');
// you can chain them together as well
// a full list of methods can be found:
// http://mongoosejs.com/docs/api.html#query-js
query.where('age').gt(21);
// finally, when ready to execute the query, call the exec() function
query.exec(function (err, results) {
if (err) throw err;
console.log(results);
cleanup();
});
Comment.add({
title : { type: String, index: true }
, date : Date
, body : String
, comments : [Comment]
});