Mongoose and multiple database in single node.js project

前端 未结 6 2300
难免孤独
难免孤独 2020-11-22 11:58

I\'m doing a Node.js project that contains sub projects. One sub project will have one Mongodb database and Mongoose will be use for wrapping and querying db. But the proble

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 12:32

    Pretty late but this might help someone. The current answers assumes you are using the same file for your connections and models.

    In real life, there is a high chance that you are splitting your models into different files. You can use something like this in your main file:

    mongoose.connect('mongodb://localhost/default');
    
    const db = mongoose.connection;
    
    db.on('error', console.error.bind(console, 'connection error:'));
    db.once('open', () => {
      console.log('connected');
    });
    

    which is just how it is described in the docs. And then in your model files, do something like the following:

    import mongoose, { Schema } from 'mongoose';
    
    const userInfoSchema = new Schema({
      createdAt: {
        type: Date,
        required: true,
        default: new Date(),
      },
      // ...other fields
    });
    
    const myDB = mongoose.connection.useDb('myDB');
    
    const UserInfo = myDB.model('userInfo', userInfoSchema);
    
    export default UserInfo;
    

    Where myDB is your database name.

提交回复
热议问题