zoukankan      html  css  js  c++  java
  • mongoose学习

    安装mongod的时候注意环境配置,否则出错

    安装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()
            })
       })
    }
  • 相关阅读:
    java_类承继其他类的内部类例子
    java_接口和抽象类的区别
    java_数组作缓存池的不可变类实例
    C++_归并排序(纯C版)
    C++_归并排序
    C++_快速排序(纯C版本)
    C++_快速排序
    C++_直接插入排序(纯C版)
    C++_直接插入排序
    自定义比较器的用法
  • 原文地址:https://www.cnblogs.com/lipu12281/p/11898795.html
Copyright © 2011-2022 走看看