mongoose的基本使用

开始之前,没什么比过一遍官方文档更有必要的了: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 数据库。

    原文作者:gjincai
    原文地址: https://segmentfault.com/a/1190000010384051
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞