var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/mydb'
MongoClient.connect(url, function(err,db) {
if (err) {
console.log("err")
} else {
console.log("Database Connected")
}
})
.connect is striked off in VS Code
err is displayed in the VS Code terminal
Node.js node-v18.12.0-x64
Mongodb version 4.2
windows 8.1 Pro
Sometimes it happens to me also. I don't use the connect function for now (macOS). Try this one:
const client = new MongoClient(uri);
const db = client.db('defaultDB');
and use it like:
await db.collection('movies').countDocuments();
Use this code. I had the same error and now it works (found this solution from this article on official mongoDb website).
MongoClient.connect('mongodb://0.0.0.0:27017',{ useNewUrlParser: true ,useUnifiedTopology:true},function(err,connect) {
if(err){
console.log("Error!")
} else {
console.log('Database connected.')
}
})
Related
I am learning Mongoose from JavaScript Everywhere book, and this is the code I had to write:
const mongoose = require('mongoose');
const mongoose = require('mongoose');
module.exports = {
connect: DB_HOST => {
mongoose.connect(DB_HOST);
mongoose.connection.on('error', err => {
console.error(err);
console.log('MongoDB connection error. Please make sure MongoDB is running.');
process.exit();
});
},
close: () => {
mongoose.connection.close();
}
}
when i hover over connect and connection, it shows Unresolved function or method connect() and Unresolved variable connection accordingly. My guess is that the book about an older version of mongoose, and in the newest version it is simply removed. What is the new function and variable for it?
Even though it's been some time.
replace your mongoose require with this:
const mongoose = require('mongoose').default;
should solve it for WebStorm
Still, I'd recommand using mongodb instead
I'm also learning Mongoose and have the same situation as you; here's how I fixed my error – you can use it as a reference to fix your code:
const {connect: connect1} = require('mongoose')
async function connect() {
try {
await connect1('DB_HOST')
console.log('\n Connected successfully')
} catch (err) {
console.log('\n Disconnect')
}
}
module.exports = { connect }
Error occurs when trying to run the function from the mongodb website that connects code to db.
const MongoClient = require('mongodb')
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});
Error is:
client.connect(err => {
^
TypeError: client.connect is not a function
I have mongodb installed via npm and uri defined as the string they gave. Do I need anything else?
The reason is that you should import the MongoClient class:
const MongoClient = require("mongodb").MongoClient;
Instead of the following line in your code: const MongoClient = require("mongodb");
Try connecting this way:
const { MongoClient } = require("mongodb");
const uri = "yourUri...";
const databaseName = "yourDBName";
MongoClient.connect(uri, { useNewUrlParser: true }, (error, client) => {
if (error) {
return console.log("Connection failed for some reason");
}
console.log("Connection established - All well");
const db = client.db(databaseName);
});
If you are using older version of MongoClient then try to install mongo client 2.2.33.
npm uninstall mongodb
npm install mongodb#2.2.33
If you are using the newer version (3.0 and above) of mongo client then modify the code as shown below.
let MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017', function(err, client){
if(err) throw err;
let db = client.db('test');
db.collection('devices').find().toArray(function(err, result){
if(err) throw err;
console.log(result);
client.close();
});
});
For that problem, the standard solution is to import clientPromise because versions higher than 3.9/4.0 do not have import {Mongoclient} command.
Then also, if you want to use MongoClient then,
Stop the current running server
Type npm i mongodb#3.5.9 in terminal
Restart your server by npm/yarn run dev
Now it will work
const mongodb = require('mongodb').MongoClient();
Background
Making a small web app that connects to a Mongo DB hosted with Mlab. I've created the DB on mlab, and created users with read/write permission. I've also created a users collection with several records.
The Problem
When I try and connect to the database using the code on mongo.github.io, I hit the error:
/home/ed/dev/mongo-demo/node_modules/mongodb/lib/operations/mongo_client_ops.js:466
throw err;
^
TypeError: Cannot read property 'db' of null
The Code
var MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://<user>:<pass>#ds115434.mlab.com:15434';
// Database Name
const dbName = 'princee3-music';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});
What I Have Tried
Oddly, if I connect through the shell using:
mongo ds115434.mlab.com:15434/princee3-music -u <dbuser> -p <dbpassword>
That works fine, or if I wrap the connection in an anonymous self-calling async function, it also connects.
Async Wrapper
const MongoClient = require('mongodb').MongoClient;
const mongoUrl = 'mongodb://<user>:<pass>#ds115434.mlab.com:15434/';
const dbName = 'princee3-music';
(async() => {
const client = await MongoClient.connect(mongoUrl, { useNewUrlParser: true});
const db = client.db(dbName);
db.collection('users').insertOne({
email: user.email,
pass: hashedPassword,
admin: true
}, (err, result) => {
if (err) {
reject({error: err});
} else {
resolve({message: 'okay'});
}
});
client.close();
})();
Any pointers on where I may be going wrong would be great.
The official mLab docs advise to connect like below. It has to be asynchronous , in order to wait for the connection to occur, or the client will be null, thus throwing an error saying that it can’t read property db of null.
On the other hand, you async has useNewUrlParser which might be the key to have a successful connection, see this issue
MongoClient.connect(url, { useNewUrlParser: true }).then(client => client.db())
I'm kinda new to module creation and was wondering about module.exports and waiting for async functions (like a mongo connect function for example) to complete and exporting the result. The variables get properly defined using async/await in the module, but when trying to log them by requiring the module, they show up as undefined. If someone could point me in the right direction, that'd be great. Here's the code I've got so far:
// module.js
const MongoClient = require('mongodb').MongoClient
const mongo_host = '127.0.0.1'
const mongo_db = 'test'
const mongo_port = '27017';
(async module => {
var client, db
var url = `mongodb://${mongo_host}:${mongo_port}/${mongo_db}`
try {
// Use connect method to connect to the Server
client = await MongoClient.connect(url, {
useNewUrlParser: true
})
db = client.db(mongo_db)
} catch (err) {
console.error(err)
} finally {
// Exporting mongo just to test things
console.log(client) // Just to test things I tried logging the client here and it works. It doesn't show 'undefined' like test.js does when trying to console.log it from there
module.exports = {
client,
db
}
}
})(module)
And here's the js that requires the module
// test.js
const {client} = require('./module')
console.log(client) // Logs 'undefined'
I'm fairly familiar with js and am still actively learning and looking into things like async/await and like features, but yeah... I can't really figure that one out
You have to export synchronously, so its impossible to export client and db directly. However you could export a Promise that resolves to client and db:
module.exports = (async function() {
const client = await MongoClient.connect(url, {
useNewUrlParser: true
});
const db = client.db(mongo_db);
return { client, db };
})();
So then you can import it as:
const {client, db} = await require("yourmodule");
(that has to be in an async function itself)
PS: console.error(err) is not a proper error handler, if you cant handle the error just crash
the solution provided above by #Jonas Wilms is working but requires to call requires in an async function each time we want to reuse the connection. an alternative way is to use a callback function to return the mongoDB client object.
mongo.js:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<user>:<pwd>#<host and port>?retryWrites=true";
const mongoClient = async function(cb) {
const client = await MongoClient.connect(uri, {
useNewUrlParser: true
});
cb(client);
};
module.exports = {mongoClient}
then we can use mongoClient method in a diffrent file(express route or any other js file).
app.js:
var client;
const mongo = require('path to mongo.js');
mongo.mongoClient((connection) => {
client = connection;
});
//declare express app and listen....
//simple post reuest to store a student..
app.post('/', async (req, res, next) => {
const newStudent = {
name: req.body.name,
description: req.body.description,
studentId: req.body.studetId,
image: req.body.image
};
try
{
await client.db('university').collection('students').insertOne({newStudent});
}
catch(err)
{
console.log(err);
return res.status(500).json({ error: err});
}
return res.status(201).json({ message: 'Student added'});
};
I am currently using the python-shell module in a Node based web interface. The issue I am having is mostly syntactical. The code below shows the generation of a python script.
var PythonShell = require('python-shell');
PythonShell.run('my_script.py' function (err) {
if (err) throw err;
console.log('finished');
}):
This is just an example script from here. How do I relate this to node's
var procc = require('child_process'.spawn('mongod');
procc.kill('SIGINT');
The documentation states that PythonShell instances have the following properties:
childProcess: the process instance created via child_process.spawn
But how do I acutally use this? There seems to be a lack of examples when it comes to this specific module
For example -
var python_process;
router.get('/start_python', function(req, res) {
const {PythonShell} = require("python-shell");
var options = {
pythonPath:'local python path'
}
var pyshell = new PythonShell('general.py');
pyshell.end(function (err) {
if (err) {
console.log(err);
}
});
python_process = pyshell.childProcess;
res.send('Started.');
});
router.get('/stop_python', function(req, res) {
python_process.kill('SIGINT');
res.send('Stopped');
});