Mongoose基础运行流程:
文章目录
- Mongoose基础运行流程:
- 官方 Docs 地址
- 1. 安装:
- 2. 使用:
- 2.1 目录结构:
- 2.2 初始化连接实例 [ 创建 DBHelper.js ]
- 2.2.1 链接地址书写格式[ mongoose.connect(参数格式 )]:
- 2.2.2 完整DBHelper.js
- 附:connection事件种类
- 2.3 创建Model
- 2.3.1 注意事项:
- (1): Model的使用基于Schema [ 先定义Schema ]
- (2): Mongoose Model预设默认行为!!
- (3): 解决(2)中的Modle预设默认行为
- 2.3.2 完整users.js
- 2.4 对应 Model 操作对应数据库表内容 [ 基于 2.2 , 2.3]
官方 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 serverconnected
: 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'
andonOpen
is executed on all of this connection’s models.disconnecting
: Your app calledConnection#close()
to disconnect from MongoDBdisconnected
: 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 afterConnection#close()
successfully closes the connection. If you callconn.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 aparseError
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预设默认行为
-
阻止mongoose多元化行为 : mongoose.pluralize(null)
mongoose 版本>5?
mongoose.pluralize(null)
-
基于改变Schema:
在Scehema中声明collection:
那么,基于此Schema的Modle的使用会基于collection参数值,
var schema = new Schema({ name: String }, { collection: 'actor' }); var M = mongoose.model('Actor', schema); // 此时 M 对应数据库中的actor ,而非mongoose预设行为中对应的actors!!
-
基于改变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:'绿萝南'})