Mongoose 官方文档
npm install mongoose --save
config文件夹-index.js:集中存放配置信息;
示例:
const DB_URL = 'mongodb://localhost:27017/admin';
exports.DB_URL = DB_URL;
model: mongoose Model users.js 即表示数据库users表;
不含校验:mongodb://域名:端口/数据库名称
mongoose.connect('mongodb://localhost:27017/test');
含校验:mongodb://用户名:密码@域名:端口/数据库名称
mongoose.connect('mongodb://user:password@localhost:27017/test')
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;
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'
and onOpen
is executed on all of this connection’s models.disconnecting
: Your app called Connection#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 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.const schema = new mongoose.Schema({ name: 'string', size: 'string' });
const Tank = mongoose.model('Tank', schema);
【注意!!】第一个参数是模型所针对的集合的单数名称。Mongoose会自动查找型号名称的复数小写版本。因此,对于上面的示例,模型Tank用于数据库中的 tanks
const schema = new mongoose.Schema({ name: 'string', size: 'string' });
const Tank = mongoose.model('Tank', schema);
阻止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!!
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
}
一个 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:'绿萝南'})
下一篇:2.1 多进程:进程间通信