I am trying to connect to my mongodb database, but it doesn't work : it doesn't run the callback, and no error is thrown :
var config = require('./config');
var mongoose = require('mongoose');
var schemas = require('./app/schemas');
var model = require('./app/model');
mongoose.connect(config.db_connection, function (err) {
if (err) {
throw err;
}
});
var ModModel = mongoose.model('mods', schemas.modScheme);
var query = ModModel.find();
query.exec('find', function (err, mods) {
if (err) {
throw err;
}
console.log('Retriveing mods...');
console.log(mods);
});
EDIT : This new code don't work
Here is the whole code : https://github.com/CraftYourModCorporation/RedstoneHub
(May not be complete, route getmods)
Could someone link a project that uses mongoose please ?
And output :
Important: use 'process.env.PORT' as the port and 'process.env.IP' as the host in your scripts!
debugger listening on port 15400
Process terminated
Thanks all of you, The problem was the connection string : instead of connecting using mongodb://user:pass#host/db, i had to use options. More details here : http://mongoosejs.com/docs/connections.html
Related
Hello (I hope my English is not to bad) !
I'm actually trying to start a basic database with MongoDB atlas (the online alternative), but I cannot pass the first step : connecting! I've got always the same error :
throw err;
^
Error: Missing delimiting slash between hosts and options
at parseConnectionString (C:\Users\Etudiant1\Documents\Cours\ProjetPerso\Bot\node_modules\mongodb\lib\url_parser.js:164:11)
at parseHandler (C:\Users\Etudiant1\Documents\Cours\ProjetPerso\Bot\node_modules\mongodb\lib\url_parser.js:129:14)
at module.exports (C:\Users\Etudiant1\Documents\Cours\ProjetPerso\Bot\node_modules\mongodb\lib\url_parser.js:25:12)
at deprecated (internal/util.js:47:15)
at connect (C:\Users\Etudiant1\Documents\Cours\ProjetPerso\Bot\node_modules\mongodb\lib\operations\mongo_client_ops.js:180:3)
at connectOp (C:\Users\Etudiant1\Documents\Cours\ProjetPerso\Bot\node_modules\mongodb\lib\operations\mongo_client_ops.js:284:3)
at executeOperation (C:\Users\Etudiant1\Documents\Cours\ProjetPerso\Bot\node_modules\mongodb\lib\utils.js:420:24)
at MongoClient.connect (C:\Users\Etudiant1\Documents\Cours\ProjetPerso\Bot\node_modules\mongodb\lib\mongo_client.js:168:10)
at Function.MongoClient.connect (C:\Users\Etudiant1\Documents\Cours\ProjetPerso\Bot\node_modules\mongodb\lib\mongo_client.js:372:22)
at Object. (C:\Users\Etudiant1\Documents\Cours\ProjetPerso\Bot\testMongo.js:4:13)
I've already seen some similar error on stack overflow but I didn't find a solution for my problem. My code is as following :
var MongoClient = require('mongodb').MongoClient;
var uri = "mongodb://Admin:<PASSWORD>#cluster0-shard-00-00-xm3ps.mongodb.net:27017,cluster0-shard-00-01-xm3ps.mongodb.net:27017,cluster0-shard-00-02-xm3ps.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true";
MongoClient.connect(uri, function(err, db) {
// Paste the following examples here
if(err){
throw err;
} else {
console.log("Connected");
}
db.close();
});
Thanks already !
Hey Laura welcome to StackOverflow! I've included code and explanation below:
MongoClient.connect(uri, { useNewUrlParser: true }, function(err, db) {
if (err) {
console.log("error connecting");
} else {
console.log("success connecting");
//do something like insert,update,etc.
db.close();
}
});
It looks like you are missing useNewUrlParser: true
You will want to use db.close() method after you've performed an operation
For security purpose, you may not want to write out the URL explicitly, rather store as an environment variable and reference instead.
var uri = process.env.mongoURI instead of var uri = mongodb://...
This is my first ever question on here so please excuse any abnormalities in etiquette.
I am new to Node.js and backend programming in general.
Right now I am using Node and Tedious to connect to a local SQL server. I'd like to keep my main.js file clean and so am trying to put everything related to my SQL connection in a separate js file. Below would be the simplest possible form I have for my main.js.
var http = require('http');
var sqlmodule = require('./SQLconnection');
http.createServer(function (req, res) {
sqlmodule.makeConnection();
}).listen(8080);
I then have my SQLconnection.js file.
var Connection = require('tedious').Connection;
exports.makeConnection = function () {
var config = {
userName: 'XXXXXX',
password: 'XXXXXX',
server: 'XXXXXX'
};
var connection = new Connection(config);
};
//The below code is my event listener but I don't know how
//to incorporate it as part of the module.
connection.on('connect', function(err) {
if (err) {
console.error('Connection error', err);
} else {
console.log('Connected');
}
});
I have no problems when the listener isn't present in the file, but I can't find a way to have it part of the SQLconnection.js module. I've tried adding exports and module.exports before it in a few ways but to no success. It listening for an event and not being a normal function is stumping me.
How would I go about getting the event listeners in the separate file?
I'm also trying to go about this as vanilla as possible, so I'm just using Node.js and Tedious at this point.
change
exports.makeConnection = function () {
to
function makeConnection() {
...
module.exports = {makeConnection}
As an additional change, you need to put your connection listener in the sames scope as the connection variable. Personally, I would also have makeConnection return a Promise with the connection so you are not operating on a connection that has failed/not yet connected. Something like
var Connection = require('tedious').Connection;
function makeConnection() {
var config = {
userName: 'XXXXXX',
password: 'XXXXXX',
server: 'XXXXXX'
};
return new Promise((resolve, reject) => {
var connection = new Connection(config);
connection.on('connect', function(err) {
if (err) return reject(err);
resolve(connection);
});
}
};
module.exports = {makeConnection}
The code is set up this way:
var express = require('express');
var router = express.Router();
var mongo = require('mongodb').MongoClient;
function getData(){
db.collection("collection_name").find({}).toArray(function (err, docs) {
if (err) throw err;
//doing stuff here
}
var dataset = [
{//doing more stuff here
}
];
});
}
router.get("/renderChart", function(req, res) {
mongo.connect(url_monitor, function (err, db) {
assert.equal(null, err);
getData(res);
});
});
When I run the code and trying to get to /renderChart when running, I get the "ReferenceError: db is not defined". I came across a similar case, and think it may be a similar problem caused because mongodb.connect() is called asynchronously, but I couldn't get it to work:
Express js,mongodb: "ReferenceError: db is not defined" when db is mentioned outside post function
The problem here is you don't pass the db to the function, so it's undefined.
A solution:
function getData(db, res){
db.collection("collection_name").find({}).toArray(function (err, docs) {
if (err) throw err;
//doing stuff here
}
var dataset = [
{//doing more stuff here
}
];
});
}
router.get("/renderChart", function(req, res) {
mongo.connect(url_monitor, function (err, db) {
assert.equal(null, err);
getData(db, res);
});
});
You'll probably need to pass the req at some point too, or make specific db queries. And you'll probably want to use promises or async/await to better deal with all asynchronous calls.
Its Simple Javascript.
You are using a variable db in your file, which is not defined, so it will throw an error.
You need to do something like this .
var findDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('documents');
// Find some documents
collection.find({}).toArray(function(err, docs) {
assert.equal(err, null);
assert.equal(2, docs.length);
console.log("Found the following records");
console.dir(docs);
callback(docs);
});
}
I have the same problem before, instead of passing db to routing function, My solution is to make db variable global like
var mongojs = require('mongojs')
global.db = mongojs(<mongodb url>);
then db variable can be used in any part of your code
If you're using express, put that in your app.js file and you will never have to worry about db variable anyore.
PS: some people think that using global is not a good practices, but I argue that since global is a node.js features and especially since it works, why not
node.js global variables?
You don't have tell the codes, that which database you want to use.
how to get databases list https://stackoverflow.com/a/71895254/17576982
here is the sample code to find the movie with name 'Back to the Future' in database sample_mflix > collection movies:
const { MongoClient } = require("mongodb");
// Replace the uri string with your MongoDB deployment's connection string.
const uri =
"mongodb+srv://<user>:<password>#<cluster-url>?retryWrites=true&writeConcern=majority";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const database = client.db('sample_mflix');
const movies = database.collection('movies');
// Query for a movie that has the title 'Back to the Future'
const query = { title: 'Back to the Future' };
const movie = await movies.findOne(query);
console.log(movie);
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
to get list of database, put await client.db().admin().listDatabases() on fun function. e.g.
async function run() {
try {
await client.connect();
var databasesList = await client.db().admin().listDatabases();
console.log("Databases:");
databasesList.databases.forEach(db => console.log(` - ${db.name}`));
learn MongoDB more from official docs: https://www.mongodb.com/docs
I am building rest api app using express.js and mssql module and I'm stacked with problem:
I need flexible architecture for my app. So I have this structure:
controller
--products.js
router
--api
---products.js
-settings.js
-app.js
In app.js I start express server, in router/api/products.js I set some api endpoints. But in controller I need to
1) start connection
2) start request
3) add data to request from router
And the problem is that in each file in controller I need to copy-paste same code as:
var sqlDb = require('mssql');
var settings = require('./settings');
exports.executeQuery = function (bdRole,sql,callback) {
var config = [];
switch(bdRole) {
case 'Main' : config = settings.sqlDbConfigMain; break
case 'Child' : config = settings.sqlDbConfigChild; break
default : config = null;
}
var conn = new sqlDb.Connection(config);
conn.connect()
.then(function(){
var req = new sqlDb.Request(conn);
req.query(sql)
.then(function (recordset) {
callback(recordset);
})
.catch(function (err) {
console.log(err);
callback(null,err);
});
})
.catch(function (err) {
console.log(err);
callback(null,err);
});
};
And I think that it is vary bad to copy-past code. But all my attempts to split this code to make its more flexible failed because I'm newbie.
I not found any examples which can help me(
I need not only execute query, but I need to execute procedure with table variable inside etc.
So the question is: Do I need to put the
var sqlDb = require('mssql');
var settings = require('./settings');
in each controller and continue copy-past or a more correct approach(way) exist?
I have a simple file model.js like follows:
var mongo = require('mongodb');
var mongoUri = process.env.MONGOLAB_URI ||
process.env.MONGOHQ_URL ||
'mongodb://localhost/mydb';
exports.connect = mongo.Db.connect(mongoUri, function(err, db) {
console.log("Connect to the database successfully")
});
and in my web.js I load the model using model = require('./model.js'). One werid thing is that although I did not call model.connect(), the message "Connect to the database successfully" still got logged to my console. Why is this happening and is there a way to avoid it?
EDIT:Never mind I have found a workaround:
exports.connect = function(){
mongo.Db.connect(mongoUri, function(err, db) {
console.log("Connect to the database successfully")
});
}
exports.connect = mongo.Db.connect(mongoUri, function(err, db) {
console.log("Connect to the database successfully")
});
You just called mongo.Db.connect() and assigned its result to exports.connect.
That code runs as soon as you require() the module.
Instead, you need to create a function:
exports.connect = function() { ... };