Node MongoDB execution order - node.js

I'm using collection.insert then in the callback collection.findAndModify
About 10% of the time collection.findAndModify fails to find the document I just inserted, even though it's being executed after the insert callback. Why is this possible? How do I deal with that?
I insert it, then try to modify it, but it's not there, then try to modify it again and it's there.

You should give the second command in the callback as the insert is asynchronous. If you are using the mongodb native driver for node,
collection.insert(document, function(err, records){
//call collection.findAndModify here
});
Check the docs

Related

mongoose pre update not firing

I have follow the directions in mongoose here
PostSchema.pre('update', function() {
console.log('pre update');
console.log(this);
});
it is not firing this middleware. Am I missing something here?
I have added next so it looks exactly like my pre save, however that still does nothing.
Make sure you don't define this after mongoose.model() has been called. Please also take note that findOneAndUpdate / upserts or updates won't trigger this hook. Another reason why it wouldn't execute is that validation fails. Therefore you would need to setup a pre('validate') hoke
I think you have to add the await keyword before your promise.

mongoose update not calling back instantly

I am sure this is simply a misunderstanding, but I can't figured it out :/
I am trying to update a document in mongoDB, using mongoose on a node server.
My code looks like this:
Message.update(searchQuery, updateQuery, function(err, response)
{
if(err) return handleError(err);
if(response) console.log(util.inspect(response));
});
When I first call this function, the callback is not executed and no changes are applied to the database. Effectively, the update does not happen.
When I call the function a second time, the callback from the first call returns and the changes from the fist update are applied to the DB. The callback for the second call does not return though and no changes for the second call are apllied.
When I call it for the third time, callback 2 returns and changes 2 are applied, but not callback and changes 3. And so on...
I assumed it has something to do with the mongoose function not directly executing when no callback is specified, so I tried adding an empty "options" array:
Message.update(searchQuery, updateQuery, **{}**, function(err, response){...});
or executing the update explicitly:
Message.update(searchQuery, updateQuery).exec( function(err, response){...});
The results were unchanged though.
Missing Mongoose callbacks are typically caused by the update waiting for the connection to be opened, as any calls to update, save, find, etc. will be queued up by Mongoose until the mongoose.connect call has completed.
So ensure your mongoose.connect call is being made before your call to update.
The right way to call update with mongoose is the following:
Message.update(query, update).exec(callback);
Whats exactly in your updateQuery?

where to specify "noCursorTimeout" option using nodejs-mongodb driver?

it might be obvious, but right now I'm not able to either find it in the docs or google it...
I'm using mongodb with the nodejs-driver and have a potentially long operation (> 10 minutes) pertaining to a cursor which does get a timeout (as specified in http://docs.mongodb.org/manual/core/cursors/#cursor-behaviors).
In the nodejs-driver API Documentation (http://mongodb.github.io/node-mongodb-native/2.0/api/Cursor.html) a method addCursorFlag(flag, value) is mentioned to be called on a Cursor.
However, there's no example on how to do it, and simply calling e.g.
objectCollection.find().limit(objectCount).addCursorFlag('noCursorTimeout', true).toArray(function (err, objects) {
...
}
leads to a TypeError: Object #<Cursor> has no method 'addCursorFlag'.
So how to go about making this Cursor exist longer than those 10 minutes?
Moreover, as required by the mongodb documentation, how do I then manually close the cursor?
Thanks!
The example you've provided:
db.collection.find().addCursorFlag('noCursorTimeout',true)
..works fine for me on driver version 2.14.21. I've an open cursor for 45 minutes now.
Could it be you were using 1.x NodeJS driver?
so I've got a partial solution for my problem. it's doesn't say so in the API docs, but apparently you have to specify it in the find() options like so:
objectCollection.find({},{timeout: false}).limit(objectCount).toArray(function (err, objects) {
...
}
however still, what about the cleanup? do those cursors ever get killed? is a call to db.close() sufficient?

Mongoose Model.count() does not run callback as documented

I am following almost the exact example for Model.count() from the Mongoose docs:
User.count({ type: 'jungle' }, function (err, count) {
console.log('I do not ever run');
});
This should print 'I do not ever run'. Instead, it returns a Query object - which should not happen, according to the docs, as I am providing a callback. How can I make the callback function run? Is there some circumstances where the callback is not run?
Using mongoose#3.6.17. Thanks!
Make sure you've connected to the database before calling any model functions. Mongoose will just queue up the count query until you connect otherwise.
See this question of the FAQ.

Mongoose and commander

I'm writing some scripts for some command-line manipulation of Mongoose models with commander.js (eventually, I'd like to run these tools using Cron).
Now, I've written several scripts with commander and they all work fine, but if I connect to the MongoDB database using mongoose, they script just hangs after it's done. Now, I figured the database connection is keeping node alive, so I added a mongoose.disconnect() line and it still hangs.
The only thing I found that allows me to shutdown is to use process.exit(), but I'm reluctant to just terminate the process. Is there something in particular that I should do to trigger a graceful shutdown?
My reading of the API docs implies that .disconnect() must be given a callback function. It looks like it's called for each that's disconnected and may be passed an error.
There is a check in the code to make sure it's not called if it doesn't exist when things work out, but that check isn't being run on errors, so if Mongoose received an error message from the MongoDB client, it may be leaving a connection open and that's why it's not stopping execution.
If you're only opening a single connection to the database, you may just want to call [Connection object].close() since that function correctly inserts a no-op "callback" if no callback is given, and looks like it will correctly destruct things.
(The more I look into Mongoose, the more I want to just write a thin wrapper around the MongoDB client so I don't have to deal with Mongoose's "help.")
I use the async "Series" to perform operations and then call mongoose.connection.close() on completion. It prevents callback hell and allows you to neatly perform operations either one at a time or parallel followed by a function when all the other methods have completed. I use it all the time for scripts that require mongoose but are meant to terminate after all mongoose operations are finished.
Shutdown the node program directly is hiding the symptoms, not fixing the problem!
I finally isolated the problem and found it to be with Mongoose schema definitions. If you try to shutdown the connection too soon after Mongoose schemas are defined1, the application hangs and eventually produces some weird MongDB-related error.
Adding a small timeout before running the program.parse(argv) line to run the commander application fixes the problem. Just wrap the code like so:
var program = require('commander')
, mongoose = require('mongoose')
, models = null
;
// Define command line syntax.
program
.command(...)
;
mongoose.connect(
..., // connection parameters.
function() {
// connected to database, defined schemas.
models = require('./models');
// Wait 1 second before running the application code.
setTimeout(function(){
program.parser(process.argv);
}, 1000);
}
);
1: This is my initial interpretation, I have not (yet) extensively tested this theory. However, removing Mongoose schema definitions from the application successfully prevents the application from hanging.
Actually, just using process.nextTick() instead of the setTimeout() call fixes the situation nicely!

Resources