Mongoose object refuses to save with .save() - node.js

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.

Related

Mongoose close connection issue

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

mongodb db not showing up

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)

MongoDB findOne returns null after server restart

first time posting a question here.
I have multiple post requests coming into a nodejs server per second with different IDs as strings to determine who they are from.
It works as intended most of the time but when restarting the server to push updates it fails consistently.
db.findOne({ID: req.body.ID})
.then(function(data){
if(data) // goes on and does things with the data
else {
db.insertOne(req.body, () => {
resolve(console.log("New user created"))
})
}
}) //a few other then blocks and a catch block that I don't think are relevant
I'm pretty new to all this stuff, but it seems to work exactly as I intend for most of the time besides server restarts. It will create multiple new entries per restart for the same user sometimes 3 or more before it starts to return valid values on the findOne request
I've tried putting in more findOne checks for other values but they are all returning null after a server restart.
It's a Heroku server running nodejs with express and mongodb as the only packages
the server opens a connection to Mongodb first thing
dotenv.config()
const mongodb = require('mongodb')
mongodb.connect(process.env.CONNECTIONSTRING, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, client){
module.exports = client.db().collection('userdata')
const app = require("./app")
app.listen(process.env.PORT)
})
and I included the collection name in "db" since I only ever use one collection.
edit:
I can't recreate the problem with only one user sending post requests, it only happens when multiple users are sending post requests and the node js server is being restarted

Waiting for PouchDB get to get a synced version from the server

I am using PouchDB to sync a database between a device and a server.
When installing my App on a new device I need to pull down the user's settings document from the server. If I do the following on a new device when the App has previously been run on another device and created the user settings:
var _DB = new PouchDB(localDBName);
_DB.sync(realRemoteDB, options);
_DB.get(userSettingsDocumentName);
The _DB.get says the document doesn't exist. If I wait long enough the sync works and the server docs are loaded locally and the .get works. How can I handle this other than putting in a long timeout?
PouchDB functions are mostly asynchronous. This means that when you fetch the document, the sync might not be complete yet.
Here's how you should write it with promises:
var _DB = new PouchDB(localDBName);
_DB.sync(realRemoteDB, options).on('complete',function(info){
//Sync is complete
return _DB.get(userSettingsDocumentName);
}).then(function(doc){
//Here you will have the document
}).catch(function(err){
//An error occured
})

Mongoose Model.find() hangs when not connected to database

I'm going through a few error scenarios, trying to understand how to handle those.
In the case where there is no database connection, a Mongoose Model.find(...) call seems to hang. Below the example code. I would have assumed that the callback is invoked with an err object, but it is not.
How can I prevent the model call to hang? Do I manually have to check the readyState each time I access a model?
// app.js
// Let's use a non-existing host so connecting fails:
// (callback is invoked with err object)
mongoose.connect('mongodb://localhostXXX/blog', function(err){ ... });
BlogPost = mongoose.model('BlogPost', BlogPostSchema);
// api.js
exports.list_posts = function(req, res) {
// Ready state is '0' = disconnected (since we used a wrong hostname)
console.log('DB ready state: ' + BlogPost.db.readyState);
// This will not invoke the callback:
BlogPost.find(function(err, threads) {
// Never called...
});
}
It is not an answer, but hope it will help you to find solution. Had very similar issue with
mongoose.createConnection
while using passport module, found out that it works fine with
mongoose.connect
Since you're already using an error handler in the connect call, a sensible thing would be to quit your app when the DB is not up, or activate some middleware that responds with a pretty 500 Internal Server Error.
Mongoose uses node-mongodb-native under the hood for connections to mongodb, you might find other useful connection options in there. :)
EDIT: try setting socketOptions.socketTimeoutMS. Apparently there is no default timeout set. See http://mongodb.github.com/node-mongodb-native/api-generated/server.html.
I don't have node on my work machine to try out the exact syntax for you, but you will probably have to use mongoose.Connection, which has an open() method that accepts options to pass through to node-mongodb-native. I don't think mongoose.connect() accepts these options, but I could be wrong.
In order to solve this problem you need to do 3 tasks:
Configure the bufferMaxEntries:0 in the options.db section (for more details see here)
So when disable bufferMaxEntries this causes mongoose to stop buffer commands and retrying to send them when the server is down.
Configure the autoReconnect:false in the options.db section
disable autoReconnet in the db level. (see more information here)
if you are working with mongodb replicaset then you need to disable bufferCommands in the schema level (for each schema you create)
var schema = new Schema({..}, { bufferCommands: false });

Resources