Cannot read properties of undefined (reading ‘db’) - javascript

My mongodb info etc. I entered it correctly, but every time I try to run the code, I keep getting this error. Attached is some of my code and a picture of the error.
error
Source Code
const vars = require("../variables");
const url = vars.dbLink; // vars.dbLink
const dbName = "channels";
var database;
const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true });
function connect(callback) {
MongoClient.connect(url, { useNewUrlParser: true }, (err, res) => {
const db = res.db(dbName);
database = db;
return callback(err);
});
}

Related

Node JS : use mongodb on imported module

I have a app.js that connect to a mongodb database an display it with express.My app.js is starting to be quite long. So I'm trying to do "modular design". I need to do a "timer.js" that will do some stuff in my mongodb with a timer.
I want to import this function from "checking.js" but this file require mongodb, some constant from DOTENV etc. so I need a import/export relation between them. How to do it ?
App.js (main file)
require('dotenv').config()
const POWER = process.env.POWER;
var mongoDb = require('mongodb');
var mongoClient = mongoDb.MongoClient;
const serverUrl = process.env.ENV_SERVEUR_MONGO_URL;
const useDB = process.env.ENV_MONGO_DATABASE;
app.get('/top', function (req, res) {
var resultArray = [];
mongoClient.connect(serverUrl, function (err, client) {
var db = client.db(useDB);
if (err) throw err;
var cursor = db.collection('top').find().sort({ _id: -1 });
cursor.forEach(function (doc, err) {
resultArray.push(doc);
}, function () {
client.close();
res.render('pages/top', { items: resultArray })
});
});
});
var checking = require('./checking')
Checking.js
function checkingdatabase() {
// ERROR require mongodb, variable undefined etc.
mongoClient.connect(serverUrl, function (err, client) {
var db = client.db(useDB);
if (err) throw err;
//do stuff
});
}
setInterval(checkingActiveOffer, 5000);
module.exports = Object.assign({ checkingdatabase })```
create DB.js file and share MongoDB connection
mongoose.connect(process.env.ENV_SERVEUR_MONGO_URL;, { useFindAndModify: false, useUnifiedTopology: true, useNewUrlParser: true })
.then(function (res) {
console.log('Succeeded connected to: ' + process.env.ENV_SERVEUR_MONGO_URL;);
exports.isReady = true;
exports.connection = res;
exports.con = res.connection
})
Checking.js
var db = require('./DB')
app.get('/top', function (req, res) {
db.con.collection('top').find().sort({_id:-1}).toArray()
.then(r=>{
res.render('pages/top', { items: resultArray })
})
})
You can do it in two different ways:
1 - You pass the values you need as a prop to Checking function. So this way you would pass your envs and your mongo client when you invoke Checking function. Not advisable
2 - You can, and should, declare the things you need inside the Checking file. Your envs and mongoClient can just be required there, and it will make your code cleaner.
Take a look at this code and see if that suits your use case.

Show results mongodb nodejs

i need show result in my database mongodb.
Im use mongodb.cloud atlas i already created database now i need show result in my database
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://test:test#cluster0.bvhvj.mongodb.net/*****?
retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("sample_restaurants");
// perform actions on the collection object
// need show result database in console.log
client.close();
});
Im expected result in sample_restaurants.restaurants in console.log
EDIT
Im use your answer but my problème return error
MongoError: no primary server available
this code
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://test:test#cluster0.bvhvj.mongodb.net/****?
retryWrites=true&w=majority";
client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("sample_restaurants").
collection("restaurants").find({}).toArray(function(err,result)
{
if(err) throw err;
console.log(result)
});
});
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://test:test#cluster0.bvhvj.mongodb.net/*****?
retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("sample_restaurants").
collection("restaurants").find({}).toArray(function(err,result)
{
if(err) throw err;
console.log(result)
});
});
First improve your code to fix the error:
let db = await MongoClient.connect(MONGO_URI, { useNewUrlParser: true });
db = await db.db();
const collection = db.collection('sample_restaurants');
You have two different ways to get the data.
1- If your results are not a lot, you can get all of them in once and then print them.
const results = await collection.find({}).toArray();
console.log(results)
2- If the number of the records is something like 2 million records, you can not use it this way. Have to create a cursor and then get them one by one.
const cursor = collection.find();
while(await cursor.hasNext()) {
const record = await cursor.next();
console.log(record);
}

Pass option { useUnifiedTopology: true } to the MongoClient constructor

Does anyone know why I'm still receiving a deprecation warning even though I've already specified useUnifiedTopoology: true in my MongoClient constructor?
Thank you in advance!
const mongodb = require('mongodb')
const MongoClient = mongodb.MongoClient
const connectionURL = 'connectionurl'
const databaseName = 'db'
const client = new MongoClient(connectionURL, { useNewUrlParser: true, useUnifiedTopology: true});
const insertHandler = async(data, collectionName) => {
await client.connect().then(async() => {
const collection = client.db(databaseName).collection(collectionName)
await collection.insertOne(data)
}).catch(error => {
console.log("Failed to insert:", error)
})
}
module.exports = {
insertHandler: insertHandler
}
And I'm getting the following error:
DeprecationWarning: current Server Discovery and Monitoring engine
is deprecated, and will be removed in a future version. To use the
new Server Discover and Monitoring engine, pass option { useUnifiedTopology:
true } to the MongoClient constructor.
You can do it this way
var mongoDb = require('mongodb');
var mongoClient = mongoDb.MongoClient;
var serverUrl = "mongodb://127.0.0.1:27017/";
var dbName = "sample_db";
mongoClient.connect(serverUrl, { useNewUrlParser: true, useUnifiedTopology: true }, function (err, db) {
// Code goes here...
});
I'm using Mongoose for MongoDB, the same code with no error. mongoose.connect("mongodb://localhost:27017/YOURDB", { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.connect('mongodb://localhost/vidly',
{ useNewUrlParser: true , useUnifiedTopology: true })
.then(()=>{ return console.log("Connected to MongoDB Localhost...");
})
.catch(err => console.log("Could not connect",err))
It's working for me!!!
This is what I used and it worked for me:
const mongoServer = require('mongodb');
const mongoClient = mongoServer.MongoClient;
const dbName = 'tconnect';
const serverUrl = 'mongodb://localhost:27017/';
// Create a database
const dbUrl = serverUrl + dbName;
const client = new mongoClient(dbUrl, { useUnifiedTopology: true });
client.connect( (err, db) => {
if (err) {
console.log(err);
return;
}
else {
console.log('Database successfully created!');
db.close();
}
});
I tried it, and this is the solution which worked:
mongoose.connect("mongodb://localhost:27017/fruitsDB", { useNewUrlParser: true, useUnifiedTopology: true });
Kind regards,
I use it this way, and I don't see that warning anymore.
const run = async () => {
await mongoose.connect(keys.mongoURI, {
useNewUrlParser: true,
useUnifiedTopology: true
});
};
run().catch(error => console.error(error);
https://github.com/Automattic/mongoose/issues/8169
this is the reference to solve this problem
const assert = require('assert');
const mongoose = require('mongoose');
mongoose.set('debug', true);
const GITHUB_ISSUE = `gh8169`;
const connectionString = `mongodb://localhost:27017/${ GITHUB_ISSUE }`;
const { Schema } = mongoose;
run().then(() => console.log('done')).catch(error => console.error(error.stack));
async function run() {
console.log('Mongoose version:', mongoose.version);
mongoose.set('useUnifiedTopology', true);
mongoose.set('useNewUrlParser', true);
mongoose.connect(connectionString, { useFindAndModify: false });
const db = mongoose.connection;
db.once('open', () => console.log('connected'));
}
Write as below:
mongoose.connect('mongodb://localhost:27017/contactlist', { useNewUrlParser: true, useUnifiedTopology: true });

Why is my callback not working correctly?

This method runs at node server
const express = require("express");
const app = express();
const fs = require("fs");
const connectDb = require("./config/db");
const __init__ = (local = false) => {
fs.writeFile(
"./config/default.json",
`{
"mongoURI": ${
local
? `"mongodb://127.0.0.1:27017/test"`
: `"mongodb+srv://admin:<password>#abc-xxghh.mongodb.net/test?retryWrites=true&w=majority"`
}
}`,
function(err) {
if (err) {
return console.log(err);
}
connectDb();
}
);
};
__init__(true);
The problem is that if originally mongoURI: 127.0.0.1:27017, and if I do __init__(false), Node will try to connect to 127.0.0.1:27017, when it should be connecting to +srv uri.
If I run __init__(false) AGAIN, then it will connect to appropriate link.
Likewise, if I then run __init__(true), it will connect to srv+ when it should be connecting to local, and if I run __init__(true) again, only then it will connect to local.
What am I doing wrong here? I'm using the callback as Im supposed to, no?
Edit:
//config/db
// for mongoDB connection
const mongoose = require("mongoose");
// require the directory
const config = require("config");
// get all contents of JSON file
const db = config.get("mongoURI");
const connectDb = async () => {
try {
console.log("connecting to mongodb", db);
await mongoose.connect(db, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
});
console.log("Mongo DB connected");
} catch (err) {
console.log("unable to connect to mongodb");
console.log(err.message);
//exit if failure
process.exit(1);
}
};
module.exports = connectDb;
I've even tried doing the following:
.....
console.log("Developing locally:", local);
// require the directory
const config = require("config");
// get all contents of JSON file
const db = config.get("mongoURI");
connectDb(db);
.....
But it still reads the old value
The problem is on execution order since the require is sync
The order now is:
const connectDb = require("./config/db");
const config = require("config");
const db = config.get("mongoURI"); // this has the OLD VALUE
fs.writeFile(...
await mongoose.connect(db, { // this is using the OLD REFERENCE
So you need to change your connectDb function like this:
const connectDb = async () => {
const config = require("config");
// get all contents of JSON file
const db = config.get("mongoURI");
try {
console.log("connecting to mongodb", db);
await mongoose.connect(db, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
});
console.log("Mongo DB connected");
} catch (err) {
console.log("unable to connect to mongodb");
console.log(err.message);
//exit if failure
process.exit(1);
}
};
Anyway, I think this is not a nicer way to load config based on the environment, so I would suggest improving it using factory pattern.
Your code for URL local vs srv+ is correct. Problem i could see is placement of method connectDb();
fs.writeFile("fir arg - URL", "second -content", third - error fun {});
where in your code after function, connectDb() is placed after error fun. After it should be closed.

How to get data from MongoDB with mongoose

I am writing CLI in which user can get any collection from MongoDB by entering the name of this connection to the console.
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const db = mongoose.connect('mongodb://paito:-----mlab.com:22222/paito', { useNewUrlParser: true });
const getCollection = (collection) => {
db.getCollection(collection)
.exec((err, data) => {
// assert.equal(null, err);
console.info(data);
console.info(`${data.length} matches`);
db.close();
})
};
module.exports = {
getCollection
};
I need to get this data to the console. The actual error "TypeError: db.getCollection is not a function".

Categories