I am new to mongodb and mongoose. I used the below code from internet. I never created the database MEANSTACK which i am referring below. When saving the record it never complained that DB or collection does not exist like it used to happen in MYSQL. How do i make sure that DB or collection exists before doing any operation and its not created automatically.
var mongoose = require( 'mongoose' );
var dbURI = 'mongodb://localhost/MEANSTACK';
mongoose.connect(dbURI);
mongoose.connection.on('connected', function () {
console.log(chalk.green('Mongoose connected to ' + dbURI));
});
mongoose.connection.on('error',function (err) {
console.log(chalk.red('Mongoose connection error: ' + err));
});
mongoose.connection.on('disconnected', function () {
console.log(chalk.red('Mongoose disconnected'));
});
Sry for writing my note as an answer. I can't write comments because my repo is below 50. When you run your server and it runs with no mistakes, that means your database var dbURI = 'mongodb://localhost/MEANSTACK' exists or at least your mongodb server is accessible. Otherwise you would get an error:
failed to connect to server [localhost:27017] on first connect
And additionally mongoose creates a db if it doesn't exist on server run, so it do the check you need on server run like "out of the box"
Related
I am using NextJS to build an app. I am using MongoDB via mongoosejs to connect to my database hosted in mongoAtlas.
My database connection file looks like below
import mongoose from "mongoose";
const MONGO_URI =
process.env.NODE_ENV === "development"
? process.env.MONGO_URI_DEVELOPMENT
: process.env.MONGO_URI_PRODUCTION;
console.log(`Connecting to ${MONGO_URI}`);
const database_connection = async () => {
if (global.connection?.isConnected) {
console.log("reusing database connection")
return;
}
const database = await mongoose.connect(MONGO_URI, {
authSource: "admin",
useNewUrlParser: true
});
global.connection = { isConnected: database.connections[0].readyState }
console.log("new database connection created")
};
export default database_connection;
I have seen this MongoDB developer community thread and this GitHub thread.
The problem seems to happen only in dev mode(when you run yarn run dev). In the production version hosted on Vercel there seems to be no issue. I understand that in dev mode the server is restarted every time a change is saved so to cache a connection you need to use as global variable. As you can see above, I have done exactly that. The server even logs: reusing database connection, then in mongoAtlas it shows like 10 more connections opened.
How can I solve this issue or what am I doing wrong?
I made a site with Meteor and it works perfectly on localhost, but not on the server. I have a collection in my mongoDB that I fill using a python-script, this script filled both my local as server mongoDB. I can see that it is filled using a database manager. However the call in my localhost prints an array with the documents, the same code/action on the website on the server returns an empty array.
I really have no clue what the problem could be, somebody that can help me figure this out?
python-script, same for local as on server!
def write_data(documents, collection_name):
# when running locally
#client = pymongo.MongoClient("localhost", 3001)
#db = client.meteor
# on the server
client = MongoClient(mongoURL, username=****,
password=****)
db = client.mercurius
if collection_name in db.collection_names():
collection = db[collection_name]
collection.drop()
new_collection = db[collection_name]
new_collection.insert_many(documents)
cursor = new_collection.find({})
for document in cursor:
print(document)
I use mup to setup the containers, it works for the other things, my code. mongoURL in mup is same as in this script above.
Meteor.call( 'getDBinfo', function(err, response){
console.log(response);
console.log(err);
});
The above call in meteor returns a full array(53 documents) on localhost, empty on server. Both have an undefined err.
Quite simply, I'm trying to connect to a MongoDB via Node.js:
Db = require('../v2/node_modules/mongodb').Db
Connection = require('../v2/node_modules/mongodb').Connection
Server = require('../v2/node_modules/mongodb').Server
console.log "before"
DbServer = new Server("localhost", 27017, {})
db = new Db("twitter", DbServer, {native_parser:true})
console.log "after"
return
That's my code and it's as simple as it gets. My output, however, seems to stop at the db = new Db... line.
It never gets to the after. It doesn't give an error either. I know I have a DB running and when I fire up MongoHub, it's there along with the twitter database
Just remove the native_parser=true would be ok
Native bson parser not compiled, please compile or avoid using native_parser=true
i have installed mongodb (1.8.3) on two seperate servers and set them up to use "replica sets" as found here: http://www.mongodb.org/display/DOCS/Replica+Set+Tutorial
everything looks good so far: one server is recognized as primary, one as secondary (when i access them via commandline).
the problem is that i can't connect to the DB using node.js (0.4.10) and mongoose (2.1.0) like this:
var mongo = require('mongoose');
mongo.connectSet('mongodb://host/dbname,mongodb://host2/dbname');
i always get the following error message:
TypeError: Cannot read property 'reconnectWait' of undefined
at new <anonymous> (/var/www/node/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connections/repl_set_servers.js:23:31)
at NativeConnection.doOpenSet (/var/www/node/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js:80:18)
at NativeConnection.openSet (/var/www/node/node_modules/mongoose/lib/connection.js:252:8)
at Mongoose.connectSet (/var/www/node/node_modules/mongoose/lib/index.js:116:27)
...
searched around a bit and found a post somewhere saying that i also have to supply the name of the replica set - so i tried this instead:
mongo.connectSet('mongodb://host/dbname,mongodb://host2/dbname', rs_name:"name_replicaset"});
what am i doing wrong here ...?!
ok, there was an error in the https://github.com/christkv/node-mongodb-native module. it's fixed now but not yet pushed to NPM. so for all you guys getting the same error, here is the fix:
https://github.com/christkv/node-mongodb-native/pull/340
after that, you can just say
var mongo = require('mongoose');
mongo.connectSet('mongodb://host:27018/testdb, host2:27017/testdb, host3:27019/testdb', function (err) {
if (err) {
console.log("could not connect to DB: " + err);
}
});
mongo.connection.on('open', function () {
console.log("mongodb connection open");
}
I've come across a node chat example on github, When I try to run it, I see the following error:
Error connecting to mongo perhaps it isn't running ?
I've installed mongo 0.9.2, nodejs 5.2 pre, npm 3.0 and other dependencies. The example can be found here: https://github.com/gregstewart/chat.io
I can not determine whether if the example not really works or I didn't run it right. Please help.
Did you install and start mongo-db on your system? This error is mostly because of a missing mongo instance running on the local machine.
Check out the follwing code excerpts from chat.io.
main.js:
/**
* Configure the user provider (mongodB connection for user data storage)
*/
var userProvider = new UserProvider('localhost', 27017);
Creates a new UserProvider object using host and port for database (localhost:27017, mongo-db default).
UserProvider.js:
UserProvider = function(host, port) {
this.db = new mongo.Db('node-mongo-chat', new Server(host, port, {auto_reconnect: true}, {}));
this.db.addListener('error', function(error) {
console.log('Error connecting to mongo -- perhaps it isn\'t running?');
});
this.db.open(function() {
});
};
Opening the connection to the server, printing out an error on failure (the error you mentioned above).
Consider reading up on the mongo-db docs concerning installation and setup here