Mongoose【node.js的优雅mongodb对象建模】

Mongoose基础运行流程:

官方 Docs 地址

Mongoose 官方文档

1. 安装:

npm install mongoose --save

2. 使用:

2.1 目录结构:

在这里插入图片描述

  • config文件夹-index.js:集中存放配置信息;

    示例:

    const DB_URL = 'mongodb://localhost:27017/admin';
    exports.DB_URL = DB_URL;
    
  • model: mongoose Model users.js 即表示数据库users表;


2.2 初始化连接实例 [ 创建 DBHelper.js ]


2.2.1 链接地址书写格式[ mongoose.connect(参数格式 )]:

不含校验:mongodb://域名:端口/数据库名称

mongoose.connect('mongodb://localhost:27017/test');

含校验:mongodb://用户名:密码@域名:端口/数据库名称

mongoose.connect('mongodb://user:password@localhost:27017/test')

2.2.2 完整DBHelper.js

const mongoose = require('mongoose');

const config = require('./index');
const { DB_URL } = config;

/* 
    捕捉建立初始连接时的错误 
    注意:两种错误捕捉注意区分,避免遗漏
    	1. 捕捉建立初始连接时的错误 
    	2. 捕捉建立初始连接[ 后 ]的错误;
*/
async function main() {
    await mongoose.connect(DB_URL);

    // use `await mongoose.connect('mongodb://user:password@localhost:27017/test');` if your database has auth enabled
}
main().catch(err => console.log(err));

/* 
    监测连接成功
*/
mongoose.connection.on('connected', () => {
    console.log('连接成功')
});
/* 
    捕捉建立初始连接[ 后 ]的错误;
*/
mongoose.connection.on('error', err => {
    logInfo(err, 'error');
});
/* 
    监测断开链接
*/
mongoose.connection.on('disconnected', back => {
    logInfo(back, 'disconnected');
});

const logInfo = (err, which) => {
    console.log(err + '-' + which)
}

exports.mongoose = mongoose;

附:connection事件种类

mongoose.connection事件 - Connection Events

  • connecting: Emitted when Mongoose starts making its initial connection to the MongoDB server
  • connected: Emitted when Mongoose successfully makes its initial connection to the MongoDB server, or when Mongoose reconnects after losing connectivity. May be emitted multiple times if Mongoose loses connectivity.
  • open: Emitted after 'connected' and onOpen is executed on all of this connection’s models.
  • disconnecting: Your app called Connection#close() to disconnect from MongoDB
  • disconnected: Emitted when Mongoose lost connection to the MongoDB server. This event may be due to your code explicitly closing the connection, the database server crashing, or network connectivity issues.
  • close: Emitted after Connection#close() successfully closes the connection. If you call conn.close(), you’ll get both a ‘disconnected’ event and a ‘close’ event.
  • reconnected: Emitted if Mongoose lost connectivity to MongoDB and successfully reconnected. Mongoose attempts to automatically reconnect when it loses connection to the database.
  • error: Emitted if an error occurs on a connection, like a parseError due to malformed data or a payload larger than 16MB.
  • fullsetup: Emitted when you’re connecting to a replica set and Mongoose has successfully connected to the primary and at least one secondary.
  • all: Emitted when you’re connecting to a replica set and Mongoose has successfully connected to all servers specified in your connection string.

2.3 创建Model

2.3.1 注意事项:

(1): Model的使用基于Schema [ 先定义Schema ]
const schema = new mongoose.Schema({ name: 'string', size: 'string' });
const Tank = mongoose.model('Tank', schema);
(2): Mongoose Model预设默认行为!!

【注意!!】第一个参数是模型所针对的集合的单数名称。Mongoose会自动查找型号名称的复数小写版本。因此,对于上面的示例,模型Tank用于数据库中的 tanks

const schema = new mongoose.Schema({ name: 'string', size: 'string' });
const Tank = mongoose.model('Tank', schema);
(3): 解决(2)中的Modle预设默认行为
  1. 阻止mongoose多元化行为 : mongoose.pluralize(null)

    mongoose 版本>5?

    mongoose.pluralize(null)
    
  2. 基于改变Schema:

    在Scehema中声明collection:

    那么,基于此Schema的Modle的使用会基于collection参数值,

    var schema = new Schema({ name: String }, { collection: 'actor' });
    var M = mongoose.model('Actor', schema);
    // 此时 M 对应数据库中的actor ,而非mongoose预设行为中对应的actors!!
    
    
  3. 基于改变Model:

    var M = mongoose.model('Actor', schema, 'actor');
    // 此时 M 对应数据库中的actor ,而非mongoose预设行为中对应的actors!!
    

2.3.2 完整users.js

const { mongoose } = require('../config/DBHelper')

const Schema = mongoose.Schema;

const UsersSchema = new Schema({
    'name': String,
    'age': Number,
    'gender': String
})

/* 
    默认添加 第1参数复数名称的表;除非指定第3参数:数据库表名
*/
const Users_Model = mongoose.model('user', UsersSchema, 'user');


const add = async (params) => {
    const addResult = await new Users_Model(params).save();
    console.log(addResult, 'Users_Model-addResult')
}


const find = async (params) => {
    const findResult = await Users_Model.find(params);
    console.log(findResult, 'Users_Model-findResult')
}

const updateOne = async (query, data) => {
    const updateOneResult = await Users_Model.updateOne(query, data);
    console.log(updateOneResult, 'Users_Model-updateOneResult')
}

const deleteOne = async (query) => {
    const deleteOneResult = await Users_Model.deleteOne(query);
    console.log(deleteOneResult, 'Users_Model-deleteOneResult')
}



exports.Add_Users = add;

exports.Find_Users = find;

exports.UpdateOne_User = updateOne;

module.exports = {
    DeleteOne_User: deleteOne,
    Add_Users: add,
    Find_Users: find,
    UpdateOne_User: updateOne
}


2.4 对应 Model 操作对应数据库表内容 [ 基于 2.2 , 2.3]

一个 Model 对应数据库一个表;

示例:针对users表使用封装好的方法[users.js]进行操作;

const { Add_Users, Find_Users, UpdateOne_User, DeleteOne_User } = require('./model/users')


Add_Users({
  name: '绿萝南',
  age: 12,
  gender: '男'
})

Find_Users();

UpdateOne_User({ name: 'baidu.com' }, { name: '南南', age: 88 })

DeleteOne_User({name:'绿萝南'})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值