Mongoose 操作MongoDB

在node.js环境下使用mongoose操作数据库MongoDB

· 简介

想要使用mongoose,首先得安装MongoDB数据库,以及了解MongoDB数据库。

可参考:http://blog.csdn.net/WaterSprite_ct/article/details/78019494

Github:https://github.com/Automattic/mongoose

API docs:http://mongoosejs.com/docs/api.html


· mongoose安装

npm install mongoose --save

与其他的模块安装一样


· 链接数据库

链接数据库前,需启动mongoDB服务,通过命令  mongod 启动服务

第一种:connect与connection结合

var mongoose = require('mongoose');
var db_url = 'mongodb://localhost/course';
/*数据库路径的格式:mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/mydatabase*/
/*链接数据库*/
mongoose.connect(db_url, {
 useMongoClient: true 
}); 
/*useMongoClient 默认值为false,设置为true,表示使用新的mongoose的connection逻辑*/
var db = mongoose.connection;
db.on('error', function(error){
	console.log('Mongodb connect error!'+error);
});
db.on('open', function(){
	console.log('Mongodb started! ');
});

第二种:createConnection


connect :  mongoose的默认连接

connect(uri [, options] [, options.useMongoClient] [, callback] );

详细可见: http://mongoosejs.com/docs/api.html#index_Mongoose-connect

可连接多个mongos


createConnection : 创建一个Connection的实例

createConnection( [ uri ], [ options ], [ options.config ], [ options.config.autoIndex ], [ options.useMongoClient ] )

每个连接实例都可映射到单个数据库。更有利的通过实例的方法管理多个数据库。通过数据库,服务器,replset选项来驱动程序。

· Schema

schema是mongoose的数据模式,用于定义数据库的字段类型。每个schema都会映射到mongodb中的一个collection。schema不具备操作数据库的能力,只是进行数据结构的定义。

定义数据结构(可定义一个icons的Schema,命名icon.js)

var mongoose = require('mongoose');

/*定义数据模式*/
var IconSchema = new mongoose.Schema({
    name: String,
    number: Number,
    meta: {
        createAt: {
            type: Date,
            default: Date.now()
        },
        updateAt: {
            type: Date,
            default: Date.now()
        }
    }
    /*更新时间的*/
});

/*为文档定义方法*/
IconSchema.pre('save', function (next) {
    /*判断是否为新添加的数据*/
    if(this.isNew){
        this.meta.createAt = this.meta.updateAt = Date.now();
    }else{
        this.meta.updateAt = Date.now();
    }
    next();
});
/*定义一些静态的方法*/
IconSchema.statics = {
    fetch: function (skip, limit, cb) {
        return this
            .find({}, null, {skip: skip})
            .limit(limit)
            .sort('meta.uodateAt')
            .exec(cb)
    },
    findById: function (id, cb) {
        return this
            .findOne({_id: id})
            .exec(cb)
    },
    findByName: function (name, cb) {
        return this
            .findOne({name: name})
            .exec(cb)
    }
}
module.exports = IconSchema;

· schema types

String、Number、Boolean、Array、Buffer、Date、ObjectId、Mixed

简单的schema结构定义(demo.js)

var mongoose = require('mongoose');

/*定义数据模式*/
var DemoSchema = new mongoose.Schema({
    name: String,
    number: Number,
    array: Array,
    isShow: Boolean,
    meta: {
        createAt: {
            type: Date,
            default: Date.now()
        },
        updateAt: {
            type: Date,
            default: Date.now()
        }
    }
    /*更新时间的*/
});

module.exports = DemoSchema;

· Model

定义好了Schema,可生成model,model可对数据库进行操作。

定义icon的model,命名为icon.js

var mongoose = require('mongoose');
var IconSchema = require('../schemas/icon');
/*相对路径*/
/*通过model编译模式为模型*/
var Icon = mongoose.model('icon', IconSchema);

/*导出Movie模型 模块*/
module.exports = Icon;

· 数据库操作(model.js)

1. find(condition,[ projection ],[ options ],[ callback ])

parameters(参数):

· condition:<Object> 条件

· [ projection ] : <object> 选择返回的字段

· [ options ]:<object> 设置的选项

· [ callback ]:<function> 回调函数

eg:

var Demo = mongoose.model('demo', DemoSchema);
Demo.find({class: '1班', age: {$gte: 18}}, 'name age class', {skip: 10, limit: 20}, function (err, students) {
    if(err){
        console.log(err);
    }else {
        console.log(students);
    }
});



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值