I am trying to use MongoDB for a REST API project. Yesterday, the db worked fine and it showed up in command prompt. Now, when I run db in my mongo terminal, my database does not show up. It even says that it connected to the MongoDB when I run my server which uses this code:
const connectWithRetry = () => {
console.log('MongoDB connection with retry')
mongoose.connect("mongodb://localhost:27017/rest-tutorial", options).then(()=>{
console.log('MongoDB is connected')
}).catch(err=>{
console.log('MongoDB connection unsuccessful, retry after 5 seconds. ', ++count);
setTimeout(connectWithRetry, 5000)
})
};
I'm new to this so I am kind of unsure what to do. The code works fine and when I register new users and send data to the database, I get my desired output. However, I am unable to see the stored data in command line. What can I do?
EDIT AS REQUESTED
mongo commands run:
db
test
show collections
(nothing shows up even though I submitted data. This is also the wrong db)
Related
Am quiet new to backend and database. I have a solution currently using mongodb. It was working fine till yesterday when i starting having the connect ETIMEDOUT 13.37.254.237:27017 error. Nothing was changed in the URI path or tampered with. It just started and i have not been able to sort it out.
is there any help available please?
I have created another cluster and its working well. But my initial cluster that has datas which are live from clients is not connecting still.
My connection code
I have used these connections code but it has not worked. It was connecting fine all through yesterday but today without tampering with the code, couldn't connect to my mongodb
mongoose.connect(process.env.MONGO_URI,{ useNewUrlParser: true, useUnifiedTopology: true });
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URL);
console.log(`MongoDB Connected: ${conn.connection.host}`);
} catch (error) {
console.log(error);
process.exit(1);
}
};
my mongoose connection and the timedout error
Whenever you connect to Mongodb using IPs that keep updating from your system causes this kind of issues.
also this can be due to your network connection. So i will advice you to:
To allow connection from any IP address(but must ensure your URI is not made known to the public to avoid attack/ access from unwanted users.)
2.Check your network status(data)
3. Run the mongo URI on your atlas
I created a MEAN project in heroku.
In MongoDB I have a DB / Collection like this:
db == content / collection == android_main
I have verified that the collection is in the proper database (and not in admin) via the following MongoSH exchange:
Atlas atlas-xxxxxx-shard-0 [primary] content> use admin
switched to db admin
Atlas atlas-xxxxxx-shard-0 [primary] admin> show collections
Atlas atlas-xxxxxx-shard-0 [primary] admin> use content
switched to db content
Atlas atlas-xxxxxx-shard-0 [primary] content> show collections
android_main
In MongoDB I also have a user w/ specific privs to read this db/collection.
In the code (Node.js) I use the following connection string:
mongodb+srv://<USER>:<PASS>#<MONGO URL>/content?retryWrites=true&w=majority
The connection completes successfully. I pass in the user I mentioned above, e.g. the user with just the specific read privs on the database (content) and collection (android_main).
In the code, the mechanism I use to get the database variable via the connection and connection string specifically is:
mongodb.MongoClient.connect(process.env.MONGODB_URI, function (err, database) {
Now, in the code, in response to an `HTTP GET` I issue the following:
db.collection("android_main").find({}).toArray(function(err, docs) {
...
}
I get back this error:
ERROR: user is not allowed to do action [find] on [admin.android_main]
Question: how can I modify my code a/o setup to ensure the db.collection.find() call references the proper database? I would have thought this was taken care of in the connection, where the database is explicitly called out.
I'm going to post the following answer which solves the issue above.
I found it by just playing around with random ideas.
I'd like to thank Heroku and their pathetic documentation for turning a 30 minute task into a 3 day ordeal.
client.connect(
process.env.MONGODB_URI,
function (err, database) {
console.log("CONNECT...");
if (err) {
console.log(err);
process.exit(1);
}
db = database.db(DATABASE);
var server = app.listen(process.env.PORT || 8080,
function () {
var port = server.address().port;
console.log("CONNECT App now running on port", port);
}
);
console.log("CONNECT Done.");
}
);
Apparently, to properly set the variable db (the one which you will use in the queries later) you should note that the database you receive in the connection callback is the admin database (that which was used for auth), and from that you make the db() request passing in the database you intend to use. All of this is utterly redundant b/c we pass the database we intend to use in the connection string. What a complete CF; but it's certainly not the 1st one. Enjoy.
In my node js program, After opening mongo connection I trying to run certain query and finally trying to close connection.
group.find({group_name: "music"}, function (doc) {
// do your stuff
console.log(doc);
mongoose.connection.close();
});
But while I trying to see mongotop log, after closing the connection, its still show as connected
Here finananceManagement is the the database, which I tried to connect, If I restart the mongo service it will disapper from the log, help me to resolve this issue
To give some context: I have a Java client application that communicates high scores to a Node.js backend via sockets. All of those aspects are working correctly. The issue is that, when I run the object.save() method, it doesn't save the object in the db. It also doesn't throw any errors, and doesn't even console.log() like it's meant to.
Here is my code.
socket.on('setScore',function(data){
var workingScore = new Score(data);
console.log("WorkingScore:");
console.log(workingScore);
workingScore.save(function(err){
console.log("MADE IT THIS FAR");
if(err)
{console.log(err)}
else
{console.log("Saved!")}
})
});
None of the three console.log() handlers fire within the workingScore.save() callback.
When I create the server, I connect to my mongodb database, and this appears to work, as the mongod console shows a new connection when the server is started. The code for that is:
mongoose.createConnection('localhost','LeaderboardDB');
When I open mongo from terminal and do use LeaderboardDB then show collections nothing comes up.
I have few integration tests that use real MongoDB database version 3.2. Tests are run with Mocha and I'm dropping the test db after each test with following code. It uses Mongoose version 4.4.12 and native MongoDB Node.js driver.
afterEach((done) => {
const connection = mongoose.createConnection(config.db.host);
connection.once("open", () => {
connection.db.command({ dropDatabase: 1 })
.then((res) => done(null, res))
.catch(done);
});
})
It worked nicely until I enabled sharding in my local environment to cover that with tests as well. Dropping database started to fail randomly. Above code fails to drop my test db about on every third test run. My sharding setup is minimal and have one config server, one mongos and two mongo shards.
After I added some logging I noticed that connection.db.command({ dropDatabase: 1 }) returns { info: 'database does not exist', ok: 1 } on those failed runs. Database is not dropped because MongoDB thinks it is already dropped even it is not the case.
Am I doing it completely wrong? Is there some Mongoose / MondoDB Node.js native driver configuration or such that I'm missing here? Or is this some known problem? Any help is much appreciated.
EDIT: Same thing happens if I use MongoClient directly, so Mongoose is not causing this.