开始之前,没什么比过一遍官方文档更有必要的了:http://mongoosejs.com/

mongoose 是啥?有啥用?
mongoose 是操作 MongoDB 的一个对象模型库;它封装了MongoDB对文档操作的常用处理方法(增删改查),让 NodeJS 操作 Mongodb 数据库变得快捷灵活。

本文所用到的完整代码:源码

安装 mongoose

新建目录 s4_mongoose 和 test.js 文件:

mkdir s4_mongoose
cd s4_mongoose
touch test.js

初始化目录生成 package.json 并安装 mongoose:

npm init
cnpm install mongoose --save

连接数据库

编辑 test.js :

var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://127.0.0.1:27017/test');
db.connection.on('error', function(error){console.log('数据库test连接失败:' + error);
});
db.connection.on('open', function(){console.log('数据库test连接成功');
});

接着先打开一个 iTerm2 终端,开启 mongodb 服务:

mongod

再打开另一个 iTerm2 终端,运行 test.js:

node test.js
//成功后便会输出:数据库test连接成功

Schema/Model/Entity

没有比文档更详细的了:http://mongoosejs.com/docs/guide.html

  1. Schema:数据库集合的结构对象。

  2. Model :由Schema构造而成,可操作数据库。

  3. Entity:由Model创建的实体,可操作数据库。

看完文档后,再看看下面一段代码配合理解一下:

var mongoose = require("mongoose");
var db = mongoose.connect("mongodb://127.0.0.1:27017/test");
// var testModel = db.model('test1', testSchema); // 集合名称;集合的结构对象
var TestSchema = new mongoose.Schema({name : { type:String },age  : { type:Number, default:0 },email: { type:String },time : { type:Date, default:Date.now }
});
var TestModel = db.model("test1", TestSchema );
var TestEntity = new TestModel({name : "helloworld",age  : 28,email: "helloworld@qq.com"
});
TestEntity.save(function(error,doc){if(error){console.log("error :" + error);}else{console.log(doc);}
});

model 数据插入

在前面的数据库连接成功的前提下,我们在数据库 test 下新建一个集合 test1 、并往里面插入保存一组数据:

var testSchema = new mongoose.Schema({name: {type: String},age: {type: Number, default: 0},email: {type: String},time: {type: Date, default: Date.now}
});
var testModel = db.model('test1', testSchema); // 集合名称;集合的结构对象
// Document文档(关联数组式的对象) < Collection集合 < 数据库
// 插入保存一段数据
testModel.create([{name: "test1", age: 8},{name: "test2", age: 18},{name: "test3", age: 28},{name: "test4", age: 38},{name: "test5", age: 48},{name: "test6", age: 58, email:"tttt@qq.com"},{name: "test7", age: 68, email:"ssss@qq.com"},{name: "test8", age: 18},{name: "test9", age: 18, email:"rrrr@qq.com"},{name: "test10",age: 18}
], function (error, docs) {if(error) {console.log(error);} else {console.log('save ok');console.log(docs);}
});

find 数据查询

mongoose 提供了find、findOne、和findById方法用于文档查询。
基本语法:

model.find(Conditions,fields,options,callback(err, doc));

Conditions: 查询条件
fields: 返回的字段
options: 游标(sort,limit)
callback: 回调函数,参数doc为查询出来的结果

条件查询的基础:
$lt (小于<)
$lte (小于等于<=)
$gt (大于>)
$gte (大于等于>=)
$ne (不等于,不包含!=)
$in (包含)
$or (查询多个键值的任意给定值)
$exists (判断某些属性是否存在)
$all (全部)

具体的一些实例,代码里已有详细注释:

// find(Conditions,fields,callback);
// 省略或为空、返回所有记录;只包含name,age字段,去掉默认的_id字段;执行回调函数
testModel.find({}, {name:1, age:1, _id:0}, function(err, docs){if (err) {console.log('查询出错:' + err);} else {console.log('{}查询结果为:');console.log(docs);}
});
// 查询age大于等于28,小于等于48
testModel.find({age: {$gte: 28, $lte: 48}}, {name:1, age:1, _id:0}, function(err, docs){if (err) {console.log('查询出错:' + err);} else {console.log('$gte,$lte查询结果为:');console.log(docs);}
});
// 查询age为58、68的2条数据
testModel.find({age: {$in: [58, 68]}}, {name:1, age:1, _id:0}, function(err, docs){if (err) {console.log('查询出错:' + err);} else {console.log('$in查询结果为:');console.log(docs);}
});
// 查询name为test3、或者age为18的全部数据
testModel.find({$or: [{name: 'test3'}, {age: 18}]}, {name:1, age:1, _id:0}, function(err, docs){if (err) {console.log('查询出错:' + err);} else {console.log('$or查询结果为:');console.log(docs);}
});// step3:游标查询
// 查询name为test3、或者age为18的全部数据;但限制只查询2条数据
testModel.find({$or: [{name: 'test3'}, {age: 18}]}, {name:1, age:1, _id:0}, {limit: 2}, function(err, docs){if (err) {console.log('查询出错:' + err);} else {console.log('limit查询结果为:');console.log(docs);}
});

update 数据更新

基本使用:model.update(查询条件,更新对象,callback);

var conditions = {name: 'test1'};
var update = {$set: {age: 11 }};
testModel.update(conditions, update, function(error){if(error) {console.log(error);} else {console.log('Update success!');testModel.find({name: 'test1'}, {name:1, age:1, _id:0}, function(err, docs){if (err) {console.log('查询出错:' + err);} else {console.log('更新test1后的查询结果为:');console.log(docs);  // 更新test_update后的查询结果为空数组:[ ];// 更新test1后的查询结果为: [ { name: 'test1', age: 11 } ]// 只能更新本来已存在的数据}});}
});

remove 数据删除

基本使用:model.remove(查询条件,callback);

var conditions = {name: 'test2'};
testModel.remove(conditions, function(error){if(error) {console.log(error);} else {console.log('Delete success!');testModel.find({name: 'test2'}, {name:1, age:1, _id:0}, function(err, docs){if (err) {console.log('查询出错:' + err);} else {console.log('删除test2后的查询结果为:');console.log(docs);  // 删除test2后的查询结果为空数组:[ ];}});}
});

robomongo mongodb可视化工具

安装 mongodb 可视化工具 robomongo
在 iTerm2 开启本地mongodb后(执行mongod),打开 robomongo,新建 connection 即可连上本地的 mongodb 数据库。

mongoose的基本使用相关推荐

  1. node.js(node.js+mongoose小案例)_实现简单的注册登录退出

    一.前言 通过node.js基本知识对node.js基本知识的一个简单应用 1.注册 2.登录 3.退出 二.基本内容 1.项目结构搭建如图所示 2.这个小案列中用到了art-template子模板以 ...

  2. mongoose手动生成ObjectId

    如果需要手动生成使用mongoose.Types.ObjectId()方法. var mongoose = require('mongoose'); var id = mongoose.Types.O ...

  3. mongoose简单使用

    介绍&安装 官网:http://www.mongoosejs.net/ npm i -S mongoose 使用 1.连接mongodb&创建模型 var mongoose = req ...

  4. node mongoose_如何使用Express,Mongoose和Socket.io在Node.js中构建实时聊天应用程序

    node mongoose by Arun Mathew Kurian 通过阿伦·马修·库里安(Arun Mathew Kurian) 如何使用Express,Mongoose和Socket.io在N ...

  5. koa+mongoose基础入门

    1.mongoose基本使用 1.安装mongodb npm install mongodb 2.引入mongodb数据表,连接mongodb,通过node来对mongodb进行异步的增删改查 con ...

  6. mongoose 实用 API 总结

    2019独角兽企业重金招聘Python工程师标准>>> 一.介绍 1. 概述 mongoose 模块用于简化 node 与数据库 mongodb 之间的操作,目的是通过简便的 API ...

  7. [转] mongoose学习笔记(超详细)

    名词解释 Schema: 一种以文件形式存储的数据库模型骨架,不具备数据库的操作能力 Model: 由Schema编译而成的假想(fancy)构造器,具有抽象属性和行为.Model的每一个实例(ins ...

  8. Mongoose源码剖析:Introduction and Installation

    引言 要剖析Mongoose的源码,首先你得知道它的一些基本情况和特性.并去使用它.本文就是介绍Mongoose是个什么东西?及如何安装和使用?这里假设你知道什么web服务器软件.web服务器使用什么 ...

  9. Nodejs+Express学习二(Mongoose基础了解)

    学习Node注定少不了与数据库打交道,而MongoDB和Node可以说是绝配,这篇主要是简单介绍Mongoose这个模块. 由于本人也是边学边写的这篇文章,绝对会有新手的味道,请大神看到这里就表往下看 ...

  10. mongoose常用方法(查询篇)

    条件 $or 或关系 $nor 或关系取反 $gt 大于 $gte 大于等于 $lt 小于 $lte 小于等于 $ne 不等于 $in 在多个值范围内 $nin 不在多个值范围内 $all 匹配数组中 ...

最新文章

  1. 深入讲解 ASP+ 验证
  2. DllMain使用的注意事项
  3. pytorch 之手写数字生成网络
  4. 简单计算器 逆波兰表达式
  5. 从1.5k到18k, 一个程序员的5年成长之路(分享)
  6. vue 微信公众号支付接口_基于vue的h5项目之支付宝支付与微信支付
  7. MySQL存储引擎MyISAM和 InnoDB
  8. 杨元:CSS浮动(float,clear)通俗讲解
  9. js生成vCard,以及格式参数详细说明
  10. SCCM2012系列之十二,SCCM2012部署操作系统
  11. exception类型 java_程序员小白入门,Java如何选择异常类型?
  12. SQL触发器编写与查看
  13. 戴尔linux恢复镜像,如何从官网下载并使用系统恢复映像
  14. 《佛密诸事》第二章 宇宙诸现象
  15. C语言OJ1116,9度OJ 题目1116:加减乘除
  16. linux基础教程 ppt,Linux基础教程(1)操作系统基础 PPT
  17. HPE的通信技术集团将如何加速电信5G的普及和应用?
  18. (附源码)计算机毕业设计SSM建筑工程管理系统
  19. R语言绘制空气污染图
  20. 宏基因组学数据分析在生物医学领域的应用

热门文章

  1. Android Permission(授权)大全
  2. 继SqlPager之后推出一款可用于前台页面的分页控件--UrlPager
  3. HDU 5115 Dire Wolf 区间dp
  4. C#中的is和as操作符
  5. (转)hibernate 注解的问题(异常)集合
  6. ubuntu apache2配置详解(含虚拟主机配置方法)
  7. 如何建立你自己的Docker镜像
  8. CF1030F Putting Boxes Together
  9. Vue中的基础过渡动画原理解析
  10. MySQL中删除重复数据