前言
NPM mongoose是node.js中操作MongoDB常用到的ORM框架,本文记录一下MongoDB的配置和连接方法.
MongoDB 配置文件修改(mongod.cfg)
- 打开连接认证之前要先添加用户,否者无可用用户登录了
# 只可以在admin集合中创建特殊权限用户
$ use admin
# 下边两个权限都可以
$ db.addUser( { user: "admin", pwd: "admin", roles: [ "userAdminAnyDatabase" ] } )
$ db.addUser( { user: "root", pwd: "root", roles: [ "root" ] } )
- 主要是为了打开MongoDB的连接认证,默认是任何人都可以操作数据库(不安全),当然不打开也不影响后续操作
## 添加或取消注释 下面代码(有疑惑的可参考官方配置文档)
security:
authorization: enabled
在项目中使用时的目录结构
-
collections:存放文档模型
-
connect.js: 连接数据库
-
exec.js: 用于临时调试执行语句
-
index.js: 导出所有文档模型
部分代码
-
以node.js为例
-
person.js
module.exports = function (mongoose) {
return mongoose.model(‘Person‘, new mongoose.Schema({
name: String,
age: Number
}));
};
- connect.js
const mongoose = require(‘mongoose‘);
const mongoConfig = global.config.mongodb;
// 带认证的
mongoConfig.urls => ‘mongodb://root:yourpass@localhost:27017/dev?authSource=admin&readPreference=primary&appname=MongoDB%20Compass&ssl=false‘
// 不带认证的
mongoConfig.urls => ‘mongodb://localhost:27017/dev‘
try {
mongoose.connect(mongoConfig.urls, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
autoIndex: false, // Don‘t build indexes
poolSize: 10, // Maintain up to 10 socket connections
serverSelectionTimeoutMS: 5000, // Keep trying to send operations for 5 seconds
socketTimeoutMS: 45000, // Close sockets after 45 seconds of inactivity
family: 4 // Use IPv4, skip trying IPv6
});
mongoose.connection.on(‘connected‘, () => {
console.mongo(‘MongoDB has been established successfully‘);
});
mongoose.connection.on(‘error‘, err => {
console.mongo(‘Unable to connect to the MongoDB:‘, err);
});
} catch (e) {
console.mongo(‘Unable to connect to the MongoDB:‘, err);
}
- connect.js
require(‘./connect‘); // 创建连接
const fs = require(‘fs‘);
const path = require(‘path‘);
const mongoose = require(‘mongoose‘);
let db = {};
[
‘collections‘ // 存放文档模型的目录,可以为多个
].forEach(function (rootFile) {
fs.readdirSync(path.join(__dirname, rootFile)).forEach(function (file) {
let url = path.join(__dirname, rootFile, file);
if (fs.statSync(url).isDirectory()) { // 也可以嵌套一层目录
fs.readdirSync(url).forEach(function (subFile) {
let model = require(path.join(__dirname, rootFile, file, subFile))(mongoose);
db[model.modelName] = model;
});
} else {
let model = require(url)(mongoose);
db[model.modelName] = model;
}
});
});
module.exports = db;
增删改查
- exec.js
const mongo = require(‘./index‘);
// 以下都以person模型为例
(async () => {
try {
// 增 save
const person = new mongo.Person({
name: ‘xpp‘,
age: 19
});
const ret = await person.save();
console.log(ret);
// 增 create
// const ret = await mongo.Person.create({
// name: ‘create‘,
// age: 19
// });
// console.log(ret);
// 修改 update / updateMany
// const ret = await mongo.Person.updateMany({
// name: ‘create‘
// }, {
// $set: {
// age: 20
// }
// });
// console.log(ret);
// 查找数据 find / findOne
// const ret = await mongo.Person.find({
// name: ‘create‘
// });
// console.log(ret);
// 删除数据 remove / deleteOne / deleteMany
// const ret = await mongo.Person.remove({
// name: ‘create‘
// });
// console.log(ret);
} catch (e) {
console.log(e);
}
})();