What is the best practice to connect/disconnect to a database?

前端 未结 4 1296
抹茶落季
抹茶落季 2021-02-09 23:37

I\'d like to know how to work with connectivity to a database in MEAN stack application. In particular, when should I create a connection to a database and when should I destroy

4条回答
  •  失恋的感觉
    2021-02-10 00:17

    Its best practice to have your db connection in a separate module (db.js)

    var mongoose = require('mongoose')
    
    mongoose.connect('mongodb://localhost/dbname', function(){
        console.log('mongodb connected')
    })
    module.exports = mongoose
    

    Each model should have a separate module that takes in the db connection (post.js)

    var db = require('../db.js')
    var Post = db.model('Post', {
        username: {type: String, required: true},
        body: {type: String, required: true},
        date: { type: Date, required: true, default: Date.now }  
    })
    
    module.exports = Post
    

    Then whenever you need to use that data set just require it and make calls

    var Post = require('/models/post')
    Post.save()
    Post.find()
    

提交回复
热议问题