mongoose简介及主要操作

来源:互联网 发布:2k17mc模式奥尼尔数据 编辑:程序博客网 时间:2024/05/16 11:18

mongoose

构建在mongodb之上,提供了Schema、Model和Document对象,用起来更为方便。

==Mongoose是在node.js异步环境下对mongodb进行便捷操作的对象模型工具==

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

API Docs:http://mongoosejs.com/docs/guide.html

mongoose安装

npm install mongoose

使用mongoose
- mongoose = require(‘mongoose’)

连接

//引用mongoose对象var mongoose = require('mongoose'),    DB_URL = 'mongodb://localhost:27017/mongoosesample';/** * 连接 */mongoose.connect(DB_URL);/**  * 连接成功  */mongoose.connection.on('connected', function () {        console.log('Mongoose connection open to ' + DB_URL);  });    /** * 连接异常 */mongoose.connection.on('error',function (err) {        console.log('Mongoose connection error: ' + err);  });    /** * 连接断开 */mongoose.connection.on('disconnected', function () {        console.log('Mongoose connection disconnected');  });    //导出mongoose对象module.exports = mongoose;

初始化mongo

Schema

schema是mongoose里会用到的一种数据模式,可以理解为表结构的定义;每个schema会映射到mongodb中的一个collection,它不具备操作数据库的能力.

/** * 用户信息 */var mongoose = require('./db.js'),    Schema = mongoose.Schema;var UserSchema = new Schema({              username : { type: String },                    //用户账号    userpwd: {type: String},                        //密码    userage: {type: Number},                        //年龄    logindate : { type: Date}                       //最近登录时间});

Model

var mongoose = require('./db.js'),    Schema = mongoose.Schema;var UserSchema = new Schema({              username : { type: String },                    //用户账号    userpwd: {type: String},                        //密码    userage: {type: Number},                        //年龄    logindate : { type: Date}                       //最近登录时间});//导出模块module.exports = mongoose.model('User',UserSchema,'Users');//引用名 定义的表结构 表名引用模块User = mongoose.model('User')

Tip.以上定义的模块在接下来的代码中会被引用,文件名为user.js。

插入

  • Model.save(function(){})
var User = require("./user.js");/** * 插入 */function insert() {    var user = new User({        username : 'Tracy McGrady',                 //账号        userpwd: 'abcd',                            //密码        userage: 37,                                //年龄        logindate : new Date()                      //最近登录时间    });    user.save(function (err, res) {        if (err) {            console.log("Error:" + err);        }        else {            console.log("Res:" + res);        }    });}insert();

更新

  • Model.update(conditions, update, [options], [callback])
var User = require("./user.js");function update(){    var wherestr = {'username' : 'Tracy McGrady'};    var updatestr = {'userpwd': 'zzzz'};    User.update(wherestr, updatestr, function(err, res){        if (err) {            console.log("Error:" + err);        }        else {            console.log("Res:" + res);        }    })}update();

其中,通过_id更新可以写成:

  • Model.findByIdAndUpdate(id, [update], [options], [callback])

删除

  • Model.remove(conditions, [callback])
var User = require("./user.js");function del(){    var wherestr = {'username' : 'Tracy McGrady'};    User.remove(wherestr, function(err, res){        if (err) {            console.log("Error:" + err);        }        else {            console.log("Res:" + res);        }    })}del();

查询

  • Model.find(conditions, [fields], [options], [callback])
var User = require("./user.js");function getByConditions(){    var wherestr = {'username' : 'Tracy McGrady'};    User.find(wherestr, function(err, res){        if (err) {            console.log("Error:" + err);        }        else {            console.log("Res:" + res);        }    })}getByConditions();

范围查询示例

User.find({userage: {$gte: 21, $lte: 65}}, callback);    //这表示查询年龄大于等21而且小于等于65
条件示例 解释 $or 或关系 $nor 或关系取反 $gt 大于 $gte 大于等于 $lt 小于 $lte 小于等于 $ne 不等于 $in 在多个值范围内 $nin 不在多个值范围内 $all 匹配数组中多个值 $regex 正则,用于模糊查询 $size 匹配数组大小 $maxDistance 范围查询,距离(基于LBS) $mod 取模运算 $near 邻域查询,查询附近的位置(基于LBS) $exists 字段是否存在 $elemMatch 匹配内数组内的元素 $within 范围查询(基于LBS) $box 范围查询,矩形范围(基于LBS) $center 范围醒询,圆形范围(基于LBS) $centerSphere 范围查询,球形范围(基于LBS) $slice 查询字段集合中的元素(比如从第几个之后,第N到第M个元素)

数量查询
Model.count(conditions, [callback])

var User = require("./user.js");function getCountByConditions(){    var wherestr = {};    User.count(wherestr, function(err, res){        if (err) {            console.log("Error:" + err);        }        else {            console.log("Res:" + res);        }    })}getCountByConditions();

模糊查询

var User = require("./user.js");function getByRegex(){    var whereStr = {'username':{$regex:/m/i}};    User.find(whereStr, function(err, res){        if (err) {            console.log("Error:" + err);        }        else {            console.log("Res:" + res);        }    })}getByRegex();

上面示例中查询出所有用户名中有’m’的名字,且不区分大小写,其中用到的正则就是正则表达式正则。

其他方法

Model.distinct(field, [conditions], [callback])                  //去重Model.findOne(conditions, [fields], [options], [callback])             //查找一条记录Model.findOneAndRemove([conditions], [options], [callback])           //查找一条记录并删除Model.findOneAndUpdate([conditions], [update], [options], [callback])      //查找一条记录并更新

返回值

Mongoose中的所有回调都使用模式: callback(error, result)。如果执行查询时发生错误,则该error参数将包含错误文档,并且result 将为null。如果查询成功,error参数将为null,并且result将填充查询的结果。

db.collection.update(filter, update, options,function(){   if(err){       console.log(err);   } else{       console.log(success message);   }});var kitty = new Cat({ name: 'Zildjian' });kitty.save(function (err) {  if (err) {    console.log(err);  } else {    console.log('meow');  }});

END

2 0
原创粉丝点击