mongoose 学习之路 ( 二 )

zhaojp0 2019-06-27

Model

认识Model

Model , 是经过 Schema 所构造而来的。 除了 Schema 定义的数据库骨架之外, 还具有数据库的行为模型, 相当于是管理数据库属性和行为的一种类。

创建一个Model

// 首先创建一个Schema
var Schema = new mongoose.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:      []
});

// 利用 我们定义的 Schema, 来创建模型
 var testMOdel = mongoose.model('test', Schema);

// 这里需要注意一下哦,就是当你使用   mongoose.model()  的时候,你的mongoose使用的是默认连接, mongoose.connect('localhost', 'gettingstarted');


mongoose.connect('mongodb://localhost:27017/test'); // 链接数据库
var db = mongoose.connection;  //连接到的数据库
// 如果我们使用了自定义的连接,那么我们就必须使用db.model()
var TestModel = db.model("test1", TestSchema); //建立模型

// 第一个参数, 这里的test 就是你的文档(也就是表)的名称;
// 第二个参数是一个 Schema

构建文档(创建实例)

// 第一种
var TestEntity = new TestModel({
  name: 'zjj',
  age: 45,
  updated: new Date(),
  binary : new Buffer(0),
  living: false,
  mixed: { any: { thing: 'i want', assd:'sad'} },
  _someId: new mongoose.Types.ObjectId,
  array: [1,2,3,'dasda']
});
// 调用实例打方法 save() 存到数据库中
TestEntity.save(function (error, doc) {
  if (error) {
    console.log("error :" + error);
  } else {
    console.log(doc);
  }
});

// 第二种
var m_test = {
  name: 'zjj',
  age: 45,
  updated: new Date(),
  binary : new Buffer(0),
  living: false,
  mixed: { any: { thing: 'i want', assd:'sad'} },
  _someId: new mongoose.Types.ObjectId,
  array: [1,2,3,'dasda']
};

TestModel.create(m_test,function(err, doc){
    // 
});

查询
查询有两种方式:

一种是 直接查询 一种是 链式查询

  • 直接查询
var person = mongoose.model('person', presonSchema);

person.findOne({name: 'Meils'}, 'name occupation', function(err, result){
    if(err) {
        return handleError(err);
    }
    // 如果没有错误result就是返回的查询结果,如果有错误那么 result就是错误文档
    console.log('%s %s is a %s', person.name.first, person.name.last, person.occupation);
});
// 解释一下
查找name == Meils,返回该文档的name 和 occupation 两个属性
  • 链式查询
var person = mongoose.model('person', presonSchema);

var query = person.findOne({name: 'Meils'});

query.select('name occupation');

query.exec(function(err, result){
    if(err) {
        return handleError(err);
    }
    // 如果没有错误result就是返回的查询结果,如果有错误那么 result就是错误文档
    console.log('%s %s is a %s', person.name.first, person.name.last, person.occupation);
});

看着不过瘾嘛,那再来一对例子

Person.find({
    occupation: '/host/',
    'name.last': 'Ghost',
    age: {$gt: 17, $lt: 100},
    likes: {$in :['talking', 'singing']}
})
.limit(10)
.sort({occupation: -1})
.select({name: 1, occupation: 1})
.exec(callback);

// 同上
Person.find({occupation: /host/})
.where('name.last').equals('Ghost')
.where('age').gt(17).lt(66)
.where('likes').in(['taiking', 'singing'])
.limit(10)
.sort('-occupation')
.select('name occupation')
.exec(callback);

详细的查询api 文档
Query

更新
此处待补充哦~~

未完待续 ~~

相关推荐

hanyueqi / 0评论 2019-06-28