mongoose MongoDB

Node.js 資料庫套件 mongoose MongoDB
npm i mongoose

匯入

// Using Node.js `require()`
const mongoose = require('mongoose');

// Using ES6 imports
import mongoose from 'mongoose';

連線

const mongoose = require('mongoose');

const connectMongoDB = async () => {
  try {
    await mongoose.connect(process.env.MONGODB_URI, {
      useUnifiedTopology: true,
      useNewUrlParser: true
    });
  } catch (error) {
    console.log(error);
  }
}

module.exports = connectMongoDB;

事件

是否連線

mongoose.connection.once('open', () => {
  console.log('Connected to MongoDB');
})

參考資料