简体   繁体   中英

Mongodb, Mongoose linking multiple models in different files

I've searched around on SO for but can't seem to find the right answer for myself. I'm learning Mongodb using Mongoose and NodeJS, but I have two separate models in separate files ie: users.js and posts.js. I am trying to have mongodb query both (because they will be linked) but I don't want to open multiple connections, as I think it would be a waste of resources in production. I have tried it with multiple connections and it works (as per the docs) but there must be a better way to simply require each Schema. POSTS

//jshint esversion: 6 
const express    = require(`express`);
const mongoose   = require(`mongoose`);
const bodyParser = require(`body-parser`);
const app = express();

//Initiate body parser
app.use(bodyParser.urlencoded({extended: true}));
//initiate posts db
mongoose.connect("mongodb://localhost:27017/postDB", {useNewUrlParser: true});

//=== SCHEMAS ===//

const postSchema = new mongoose.Schema ({
    postTitle: {
        type: String,
        required:[true, `Must enter a title`],
        minlength: [1, `Title must be at least 1 chars`],
        maxlength: [120, `Title cannot be more than 120 chars`]
    },
    postDate: {
        type: Date,
        required:[false]
    },
    postBody: {
        type: String,
        required:[true, `Post must have content`],
        minlength: [1, `Content must be at least 1 chars`],
        maxlength: [50000, `Content cannot be more than 50,000 chars`]
    },
    postAuthor: {
        type: String,
    }
});

Users.js:

const express    = require(`express`);
const mongoose   = require(`mongoose`);
const bodyParser = require(`body-parser`);
const app = express();

//Initiate body parser
app.use(bodyParser.urlencoded({extended: true}));
//initiate posts db
mongoose.connect("mongodb://localhost:27017/userDB", {useNewUrlParser: true});

  //USER SCHEMA//
  {SOME STUFF}

server.js

//jshint esversion: 6 

//=== DEPENDENCIES ===//

//Application global constants
const express    = require(`express`);
const mongoose   = require(`mongoose`);
const bodyParser = require(`body-parser`);
const ejs        = require('ejs');
const _          = require(`lodash`);        
//Initiate Express
const app = express();
module.exports = app;
//Express Routing Requires()
const site = require(`./routes/siteController`);
const user = require(`./routes/userController`);
const post = require(`./routes/postController`);

//=== DEPENDENCY SETTINGS ===//

//Initiate EJS engine
app.set(`view engine`, `ejs`);
app.engine('html', require('ejs').renderFile);
//Initiate body parser
app.use(bodyParser.urlencoded({extended: true}));
//Set express static files
app.use(express.static(`public`));

Also as I am learning if you have any feedback on the code it'd be much appreciated!

I am now in the position to make an answer for my own question. Linking multiple databases to a single connection is very simple with the createConnection() mongoose method, things get slightly more unusual when you have multiple model.js files and a single server.js (or main app.js) file.

My file structure for a visual reference:

-MAIN FOLDER
 -controllers
   -userController
   -staticPagesController
   -postsController
 -models
    server.js //I CONTAIN ALL THE DATABASE AND SERVER CONNECTION TOOLS
    posts //I NEED A DB OF MY OWN
    users //I NEED A DB OF MY OWN
 -public
    stylesheets
 -views
    user
      all user ejs files
    post
      all post ejs files
    site
      all staticpage ejs files
    partials
      all partials
 -index.js

Inside your server.js file you must create two connections(one for each db) like so:

//Create connection one to userDB

const conn1Name = `userDB`;
exports.makeConn1 = mongoose.createConnection(`mongodb://localhost:27017/${conn1Name}`, {useNewUrlParser: true }, function(err){
  if (!err){
    console.log(`Database Server connection created at: ${conn1Name}`);
  } else {
    console.log(`Error starting server ${err}`);
  }
});

//Create connection one to postDB
const conn2Name = `postDB`;
exports.makeConn2 = mongoose.createConnection(`mongodb://localhost:27017/${conn2Name}`, {useNewUrlParser: true }, function(err){
  if (!err){
    console.log(`Database Server connection created at: ${conn2Name}`);
  } else {
    console.log(`Error starting server ${err}`);
  }
});

Each of your model.js files will have its own Schema inside i'll use a User as reference ie:

const userSchema = new mongoose.Schema ({
    userName: {
        type: String,
        required: [true, `Must Enter A Name`]
    }
)};

Inside here you must require your server.js file like so

const conn1 = require(`/path/to/server`);

NOW the confusing part that is so very subtle but makes all the difference! We set conn1 to require the path to the server so it can connect but we must have a model for our schema to use. We use conn1 to create the model with the following syntax:

module.exports = conn1.makeConn1.model(`User`, userSchema);

Here we directly export the the now connected model with it's associated schema to wherever we need to require it (ie: your controllers or main app.js). The subtle difference here is that we aren't creating a new mongoose.model like the documents suggest, but instead using our newly created connection to call model on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM