当前位置:网站首页>[Architect (Part 40)] connecting mongodb database developed by server
[Architect (Part 40)] connecting mongodb database developed by server
2022-06-23 10:51:00 【A tailed Warbler】
Keep creating , Accelerate growth ! This is my participation 「 Nuggets day new plan · 6 Yuegengwen challenge 」 Of the 23 God , Click to see the event details
Mongodb and Mongoose
Mongodb
Mongodb The database has been previously installed .
Create a imooc_lego_course database , One work collection.
Click on create Finish creating .
Mongoose
install
npm i mongoose -S
add to mongodb Configuration file for
module.exports = {
// mongodb Connection configuration
mongodbConf: {
host: 'localhost',
port: '27017',
dbName: 'imooc_lego_course',
},
}
encapsulation mongoose , Connect mongodb
// src\db\mongoose.js
const mongoose = require('mongoose')
const { mongodbConf } = require('../config/index')
const { host, port, dbName, user, password } = mongodbConf
// Splice connection string
let url = `mongodb://${host}:${port}` // dev Environmental Science
if (user && password) {
url = `mongodb://${user}:${password}@${host}:${port}` // prd Environmental Science
}
// Start connecting ( When using user name and password , need `?authSource=admin` )
mongoose.connect(`${url}/${dbName}?authSource=admin`, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
// Connection object
const db = mongoose.connection
db.on('error', err => {
console.error('mongoose connect error', err)
})
// perform node src/db/mongoose.js Test connection
db.once('open', () => {
// To test whether the database connection is successful
console.log('mongoose connect success')
})
module.exports = mongoose
Console execution node src/db/mongoose.js , The database is correctly connected .
newly build model
// src\models\WorksModel.js
const mongoose = require('../db/mongoose')
const WorkScheme = mongoose.Schema(
{
// mongodb It will generate automatically _id, Don't define it yourself
// title
title: String,
// Component list for page
components: [Object],
// Page properties
props: Object,
setting: Object,
},
{
timestamps: true
}
)
const WorkModel = mongoose.model('work', WorkScheme)
module.exports = {
WorkModel
}
Further test the database connection
// src\routes\index.js
const router = require('koa-router')()
const packageInfo = require('../../package.json')
const testMysqlConn = require('../db/mysql2')
const ENV = require('../utils/env')
const { WorkModel } = require('../models/WorksModel')
// Test database connection
router.get('/api/db-check', async (ctx) => {
// test mysql Database connection
const mysqlRes = await testMysqlConn()
// test mongodb Database connection
let mongodbConn
try {
mongodbConn = true
await WorkModel.findOne()
} catch (error) {
mongodbConn = false
}
ctx.body = {
errno: 0,
data: {
name: 'biz editor server',
version: packageInfo.version,
ENV,
mysqlConn: mysqlRes.length > 0,
mongodbConn
}
}
})
module.exports = router
visit http://localhost:3000/api/db-check, You can see mongodbConn The value of the field is true, This indicates that the database connection was successful .
Date And time zone
mysql and Mongodb When querying data , The time is wrong , There is an eight hour difference between them , It has something to do with the time zone .
stay nodejs in ,new Date() Will display the world standard sleep , It is eight time zones away from Beijing time , That's eight hours , Empathy , new Date('2022-06-18 14:00:00') The result is 2022-06-18T06:00:00.000Z, There is also a difference of eight hours .
If you want to get the time in the current time zone , Just use toString() that will do .
You can use some third-party libraries to format , such as date-fns
console.log('new Date()')
console.log()
console.log(new Date())
console.log()
console.log("new Date('2022-06-18 14:00:00')")
console.log()
console.log(new Date('2022-06-18 14:00:00'))
console.log()
console.log("new Date().toString()")
console.log()
console.log(new Date().toString())
The results of console printing are as follows
边栏推荐
- NOI OJ 1.4 04:奇偶ASCII值判断 C语言
- Simplest DIY mpu6050 gyroscope attitude control actuator program based on stm32f407 Explorer development board
- list的深度剖析及模拟实现
- 图片存储--引用
- Noi OJ 1.2 06: round floating point numbers to zero
- argmax函数笔记-全是细节
- 2021-05-12 interface definition and Implementation
- Noi OJ 1.3 13: reverse output of a three digit C language
- Stm32f1 and stm32subeide programming example - infrared tracking sensor driver
- NOI OJ 1.2 10:Hello, World!的大小 C语言
猜你喜欢

Installation and use of binabsinspector, an open source binary file static vulnerability analysis tool

技术创造价值,手把手教你薅羊毛篇

最简单DIY基于STM32F407探索者开发板的MPU6050陀螺仪姿态控制舵机程序

Interview Manual of social recruitment Tencent high P (Senior Product Manager)

安装typescript环境并开启VSCode自动监视编译ts文件为js文件

TTY驱动框架

当 Pandas 遇见 SQL,一个强大的工具库诞生了

一年多时间时移世易,中国芯片不断突破,美国芯片却难以卖出

Simplest DIY remote control computer system based on STM32 ② (wireless remote control + key control)

Experience of using thread pool in project
随机推荐
Stm32f1 and stm32subeide programming example - infrared tracking sensor driver
华为云·维享会交流平台简介
Set up a QQ robot for ordering songs, and watch beautiful women
Weidongshan equipment information query routine learning
Not satisfied with the effect of the smart park? Please accept this secret script of thingjs
Is the online security of securities account opening high
Mysql-03. Experience of SQL optimization in work
“互联网+”大赛命题火热对接中 | 一图读懂百度38道命题
Stockage d'images - référence
TTY drive frame
Economic common sense
Flush recommended? Is it safe to open a mobile account?
Build the information and innovation industry ecology, and make mobile cloud based on the whole stack of independent innovation
ESP32-CAM高性价比温湿度监控系统
Solve the problem of invalid audio autoplay
R and rstudio download and install detailed steps
Noi OJ 1.3 17: calculating triangle area C language
最简单DIY基于蓝牙、51单片机和舵机的钢铁爱国者机关枪控制器
Interview Manual of social recruitment Tencent high P (Senior Product Manager)
Simplest DIY remote control computer system based on STM32 ② (wireless remote control + key control)