安装mongoose,启动mongoose为mongod

npm install mongoose --save

另建文件建立Schema

const mongoose = require("mongoose")
const Schema = mongoose.Schema
let ObjectId = Schema.Types.ObjectId


const entryScheam=new Schema({
    id:Number,
    is_in_serving:Boolean,
    description: String,
    title:String ,
    link: String ,
    image_url:String ,
    icon_url: String,
    title_color: String,
    __v: Number,

})

//发布模型
mongoose.model("Entry",entryScheam)

建立初始化连接

const mongoose = require('mongoose')
const db = 'mongodb://localhost/elm-db'
const glob = require('glob')
const {resolve} = require("path")
exports.initSchemas=()=>{
  glob.sync(resolve(__dirname,'./schema/','**/*.js')).forEach(require)
}
exports.connect  = () =>{
   //数据连接
   mongoose.connect(db)
   let maxConnectTimes =  0
   return new Promise((resolve,recject)=>{
        //增加数据库连接的事件监听
        mongoose.connection.on("disconnected",()=>{
            console.log("*******数据库断开*******")
            if(maxConnectTimes<3){
                mongoose.connect(db)
                maxConnectTimes++
            }else{
                  recject()
                  throw new Error("程序出现问题请人为修理")
            }
        })

        mongoose.connection.on("error",err=>{
        console.log("*******数据库断开*******")
        if(maxConnectTimes<3){
            mongoose.connect(db)
            maxConnectTimes++

        }else{
            recject(err)
            throw new Error("程序出现问题请人为修理")
        }
        })
        mongoose.connection.once("open",()=>{
        console.log("MongDB Connected successfully!")
        resolve()
        })
   })
}
12-29 17:16