0

I have an error when I try to write into the MongoDB database, below is the error.

/root/deployme/node_modules/mongodb/lib/mongo_client.js:315
    throw new MongoError('MongoClient must be connected before calling MongoClient.prototype.db');
    ^

MongoError: MongoClient must be connected before calling MongoClient.prototype.db
    at MongoClient.db (/root/deployme/node_modules/mongodb/lib/mongo_client.js:315:11)
    at Object.<anonymous> (/root/deployme/models/user.models.js:9:19)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (/root/deployme/controllers/controller.js:3:15)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)

I call the code from my controller.js, here is the code:

exports.regUser = async (req, res) => {
  const ip = (
    req.headers["x-forwarded-for"] ||
    req.connection.remoteAddress ||
    ""
  )
    .split(",")[0]
    .trim();
  const data = req.body;
  const write = await model.writeReg(data);
  res.json(write);
}

And here is my model:

const axios = require('axios');
const helper = require('../helper');
const {MongoClient} = require('mongodb');

const uri = 'mongodb://myserver:27017/?poolSize=20&writeConcern=majority';
const client = new MongoClient(uri);
client.connect();

const db = client.db('rixca');
const userRef = db.collection('users');
const regRef = db.collection('register');
const actRef = db.collection('activity');
const cpRef = db.collection('cpanels');
const feedRef = db.collection('feedback');

exports.writeReg = async (data) => {
    const unique = helper.uniqueKey();
    const scheme = {
        uid: unique,
        email: data.email,
        expired: Date.now() + 60000,
    };
    const check = await this.checkReg(data.email);
    if(check.status === 'regisrered') {
        return {status: 400, message: "Email already in use."};
    }
    if(check.status === "wait") {
        return {status: 400, message: "Try again later"};
    }
    const recheck = await this.isExist(regRef, {email: data.email});
    if(recheck.status) {
        await regRef.deleteOne({_id: recheck.data._id});
    }
    const letStart = await regRef.insertOne(scheme);
    if(!letStart) return {status: 500, message: "Something went wrong"};
    return {status: 200, message: "We has sent you an email", uid: unique};
}

exports.checkReg = async (value) => {
    const query = {email: value}
    const user = await userRef.findOne(query);
    if(user != null) {
        return {status: 'registered'};
    }
    const regist = await regRef.findOne(query);
    if(regist === null) {
        return {status: "ready"};
    }
    if(regist.expired > Date.now()) {
        return {status: 'wait'};
    } else {
        return {status: 'ready'};
    }
}

exports.isExist = async (collection, query) => {
    if(collection == 'user') {
        collection = userRef;
    }
    if(collection == "reg") {
        collection = regRef;
    }
    const snapshoot = await collection.findOne(query);
    const status = (snapshoot != null);
    return {
        status,
        data: snapshoot,
        docId : snapshoot._id,
    };
}

I have tried to connect to MongoDB inside controller.js, but it still throws an error, so is there a way to connect to MongoDB without connecting on each function?

1 Answer 1

1

You did not use the connect() properly.

Here's some sample code but please do attempt M220JS: MongoDB for Javascript Developers

Index.js

MongoClient.connect(
  process.env.DB_URI,
  {newUserParser: true}
).catch( err => {
   console.log(err.stack)
}).then(async client => {
   await userDAO.injectDB(client)
   app.listen(3000, () => {
     console.log(`listening on port 3000`)
   })
})

UserDAO.js

let users
export default class UsersDAO {
  static async injectDB(conn) {
    if(users) {
      return
    }
    try {
      users = await conn.db(process.env.DB_NAME).collection("users")
    } catch(e) {
      console.log(e)
    }
  }
}
 
static async doesUserExist(query){
  try{
    const snapshoot = await users.findOne(query);
    const status = (snapshoot != null);
    return {
       status,
       data: snapshoot,
       docId : snapshoot._id,
    };
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.