当前位置:网站首页>[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.

image.png

Click on create Finish creating .

image.png

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 .

image.png

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 .

image.png

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

image.png

原网站

版权声明
本文为[A tailed Warbler]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231039299784.html