skip to Main Content

I’m trying create multiple connections to my mongodb Cloud.
The old code for single connection with mongoose.connect() is still fine, but when I changed to mongoose.createConnection() for multiple connections, I got this error:

TypeError: conn1.model is not a function

Edited: I’ve removed .asPromise() behind mongoose.createConnection(process.env.MONGO_URI) but it is still the same problem

My code:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
require("dotenv").config();

const conn1 = mongoose.createConnection(process.env.MONGO_URI)
const UserSchema = new Schema({
    username: {
        type: String,
        required: true,
        unique: true,
    },
    email: {
        type: String,
        required: true,
        uniquie: true,
        lowercase: true,
    },
});

module.exports = conn1.model("users", UserSchema);

2

Answers


  1. You can try using the then() method in handling successful connections to your MongoDB database. Also use handle errors

    const mongoose = require("mongoose");
    const Schema = mongoose.Schema;
    require("dotenv").config();
    
    const conn1 = mongoose.createConnection(process.env.MONGO_URI);
    conn1.then(() => {
        const UserSchema = new Schema({
            username: {
                type: String,
                required: true,
                unique: true,
            },
            email: {
                type: String,
                required: true,
                unique: true,
                lowercase: true,
            },
        });
    
        module.exports = conn1.model("users", UserSchema);
    }).catch((error) => {
        console.error("Connection error:", error);
    });
    
    Login or Signup to reply.
  2. try remove .asPromise(. I think it is usefull

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search