Node.js使用mongoose操作mongodb
发布日期:2021-07-28 08:29:52 浏览次数:3 分类:技术文章

本文共 7757 字,大约阅读时间需要 25 分钟。

软件配置:

1.node v8.9.3
2. npm 5.5.1
3. mongoose及MongoDB版本见下package.json

// package.json

{
  "name": "mongoosedemo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "mongodb": "^3.1.1",
    "mongoose": "^5.2.4"
  }
}

一、mongoose: Schema, Model, Entity
Schema : 一种以文件形式存储的数据库模型骨架,不具备数据库的操作能力
Model : 由 Schema 发布生成的模型,具有抽象属性和行为的数据库操作
Entity : 由 Model 创建的实体,他的操作也会影响数据库

三者关系:

Schema 生成 Model,Model创造 Entity;
Model 和 Entity 都可对数据库操作造成影响,但 Model 比Entity 更具操作性。

二、 连接字符串

2.1 连接字符串
// db.js

const mongoose = require('mongoose');

const DB_URL = 'mongodb://localhost:27017/mydatabase1';

// 连接

mongoose.connect(DB_URL, { useNewUrlParser: true });
// 连接成功
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 ');
})
 

// 修改上面db.js 新增最后一行,导出mongoose对象
const mongoose = require('mongoose');
const DB_URL = 'mongodb://localhost:27017/mydatabase1';

// 连接

mongoose.connect(DB_URL, { useNewUrlParser: true });
// 连接成功
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 ');
})

module.exports = mongoose;

2.2 Schema
// 定义一个user的Schema,命名为user.js

/**

 * 用户信息
 */
// 定义数据库表存储结构
const mongoose = require('./db');
const Schema = mongoose.Schema;

const UserSchema = new Schema({

  username: { type: String }, // 用户名
  password: { type: String }, // 用户密码
  age: { type: String }, // 用户年龄
  lastLoinDate: { type: Date } // 最近登录一次时间
})

2.3 Model
定义好了Schema,接下就是生成Model。
model是由schema生成的模型,可以对数据库的操作

// 修改上面的user.js,将Schema转成Model,并导出

// user.js

/**

 * 用户信息
 */
// 定义数据库表存储结构
const mongoose = require('./db');
const Schema = mongoose.Schema;

const UserSchema = new Schema({

  username: { type: String }, // 用户名
  password: { type: String }, // 用户密码
  age: { type: String }, // 用户年龄
  lastLoinDate: { type: Date } // 最近登录一次时间
})

// 生成Model

module.exports = mongoose.model('User', UserSchema);
三、 CRUD操作
3.1 插入
Model#save([fn])
新建test.js

const User = require('./user');

// 插入

function insert() {
  var user = new User({
    username: "陈二狗", // 用户名
    password: "abc123", // 用户密码
    age: 18, // 用户年龄
    lastLoinDate: new Date() // 最近登录一次时间
  });

  user.save(function (err, docs) {

    if(err) {
      console.log("Error: " + err);
    } else {
      console.log("docs: " + docs);
    }
  })
}
insert();
node test.js

3.2 更新
Model.update(conditions, update, [options], [callback])

// test1.js

const User = require('./user');

// 更新

function update() {
  var whereStr = {"username": "陈二狗"};
  var updateStr = {"password": "123456"};

  User.update(whereStr, updateStr, function (err, docs) {

    if(err) {
      console.log("Error: " + err);
    } else {
      console.log("docs: " + docs);
    }
  })
}
update();

node test1.js

常用方法还有 findByIdAndUpdate,这种比较有指定性,就是根据_id

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

// test12.js

const User = require('./user');

// 根据ID更新 

function findByIdAndUpdate() {
  var id = "5b5333a114cf2d337c6bd971";
  var updateStr = {"password": "aabbcc"};

  User.findByIdAndUpdate(id, updateStr, function (err, docs) {

    if(err) {
      console.log("Error: " + err);
    } else {
      console.log("docs: " + docs);
    }
  })
}
findByIdAndUpdate();
其它更新方法

Model.findOneAndUpdate([conditions], [update], [options],[callback])      //找到一条记录并更新

3.3 删除

Model.remove(conditions, [callback])

// test2.js

const User = require('./user');

// 删除 

function del() {
  var whereStr = {"username": "陈二狗"};

  User.remove(whereStr, function (err, docs) {

    if(err) {
      console.log("Error: " + err);
    } else {
      console.log("docs: " + docs);
    }
  })
}
del();
其它常用方法还有:
  Model.findByIdAndRemove(id, [options], [callback])      
  Model.findOneAndRemove(conditions, [options], [callback])

3.4 条件查询

  已先插入一些测试数据 。。

  Model.find(conditions, [fields], [options], [callback])

const User = require('./user');

// 条件查询

function getByConditions() {
  var whereStr = {"username": "陈二狗1"};

  User.find(whereStr, function (err, docs) {

    if(err) {
      console.log("Error: " + err);
    } else {
      console.log("docs: " + docs);
    }
  })
}
getByConditions();
 

第2个参数可以设置要查询输出的字段,比如改成

const User = require('./user');

// 条件查询(设置第二个参数)

function getByConditions() {
  var whereStr = {"username": "陈二狗1"};
  var opt = {"username": 1, "_id": 0};

  User.find(whereStr, opt, function (err, docs) {

    if(err) {
      console.log("Error: " + err);
    } else {
      console.log("docs: " + docs);
    }
  })
}
getByConditions();
 

输出只会有username字段,设置方法如上,1表示查询输出该字段,0表示不输出

3.4.1 查询年龄

const User = require('./user');

// 条件查询

function getByConditions() {
  // var whereStr = {"username": "陈二狗1"};
  // var opt = {"username": 1, "_id": 0};

  // User.find(whereStr, opt, function (err, docs) {

  // 查询年龄大于等20而且小于等于50岁
  User.find({"age": {$gte: 20, $lte: 50 }}, function (err, docs) {
    if(err) {
      console.log("Error: " + err);
    } else {
      console.log("docs: " + docs);
    }
  })
}
getByConditions();
 

3.4.2
$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个元素)
3.5 数量查询

Model.count(conditions, [callback])

const User = require('./user');

// 数量查询

function getCountByConditions() {
  var whereStr = {};

  // User.count(whereStr, function (err, docs) {

  User.countDocuments(whereStr, function (err, docs) {
    if(err) {
      console.log("Error: " + err);
    } else {
      console.log("docs: " + docs);
    }
  })
}
getCountByConditions();
 

修改后:

3.6 根据_id查询
  Model.findById(id, [fields], [options], [callback])

const User = require('./user');

// 根据_id查询

function getById () {
  var id = "5b536b314cfb3f0d54a53d37"

  User.findById(id, function (err, docs) {

    if(err) {
      console.log("Error: " + err);
    } else {
      console.log("docs: " + docs);
    }
  })
}
getById ();
 

3.7 模糊查询
新增部分数据

const User = require('./user');

// 模糊查询

// 查询出所有用户名中有'm'的名字,且不区分大小写
function getByRegex () {
  var whereStr = {"username": {$regex: /m/i}};

  User.find(whereStr, function (err, docs) {

    if(err) {
      console.log("Error: " + err);
    } else {
      console.log("docs: " + docs);
    }
  })
}
getByRegex ();
3.8 分页查询
const User = require('./user');

// 分页查询

function getByPager () {
  var pageSize = 5; // 一页多少条
  var currentPage = 1; // 当前第几页
  var sort = {'lastLoinDate': -1}; // 按登录时间倒序排
  var condition = {};
  var skipnum = (currentPage - 1) * pageSize; // 跳过数

  User.find(condition).skip(skipnum).limit(pageSize).sort(sort).exec(function (err, docs) {

    if(err) {
      console.log("Error: " + err);
    } else {
      console.log("docs: " + docs);
    }
  })
}
getByPager ();
currentPage = 1的时候

currentPage = 2的时候

3.9 其它常用方法

Model.distinct(field, [conditions], [callback])  //去重

Model.findOne(conditions, [fields], [options], [callback])   //查找一条记录
Model.findOneAndRemove(conditions, [options], [callback])  //查找一条记录并删除
Model.findOneAndUpdate([conditions], [update], [options], [callback]) //查找一条记录并更新
相关代码下载
注:

mongoose中所有回调函数都是function(err,docs)的这种形式,err是报错,docs是返回对象(或查询筛选之后)的结果

实例方法需要new才能使用(如save),静态方法在Model层即可使用(如find()、findOne()方法)
mongodb学习(3)— NodeJs使用mongoose操作mongodb
mongoosejs
mongoose学习笔记2015-7-24

Mongoose学习参考文档——基础篇

Mongoose学习参考文档——基础篇
超详细的数据库mongoose的使用方法/教程
极客学院

————————————————
版权声明:本文为CSDN博主「林飞的梦呓」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_25479327/article/details/81148772

转载地址:https://blog.csdn.net/sinat_17775997/article/details/116134221 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Elasticsear使用文档
下一篇:ElasticSearch学习笔记 | Term和Keyword精确查询

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年04月29日 03时37分22秒