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

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.

Related

I never get in the callback function, nodejs just stops

I always used nodejs together with express, but now I try to run the following script in nodejs (just by calling in the terminal "node myscript.js")
postModel is a mongoose model, doing a query on a mongodb.
'use strict'
var postModel = require(__dirname + '/../model/post').postModel;
myfunction();
function myfunction() {
console.log("before call");
postModel
.find({isArchived: false})
.exec(function(err,result){
console.log("result is ok")
})
};
so what I don't understand is why I never see "result is ok" in my terminal.
I also tried this with the async and wait.for library, but also there my script just stops before the async function is executed and a result is returned.
I think I just miss something in what I am doing, but no idea what...
You need to call mongoose.connect() to actually connect to a database.
Otherwise, Mongoose will queue your query internally and wait for a connection before issuing the query. However, since that connection never comes (because mongoose.connect() wasn't called), the queue is never processed, your query is never issued, and hence its callback will never get called.

how to use marklogic query results in node.js

I have looked around quite extensivly and could not find any example on how to use query results from the marklogic module inside node.js...
Most examples do a console.log() of results and thats it, but what if I need the query results (say in a JSON array and use these results later on?
Seems I am missing some node.js ascynch stuff here...
Example :
var marklogic = require('marklogic');
var my = require('./my-connection.js');
var db = marklogic.createDatabaseClient(my.connInfo);
var qb = marklogic.queryBuilder;
db.documents.query(
qb.where(qb.parsedFrom('oslo'))
).result( function(results) {
console.log(JSON.stringify(results, null, 2));
});
// I would like to use the results here
// console.log(JSON.stringify(results, null, 2))
Now question is I would like to use the results object later on in this script. I have tried using .then(), or passing it to a variable and returning that variable but no luck.
Regards,
hugo
Simple answer: you need to continue your business logic from the result() callback.
In more detail, your goal is to do something with the result of an asynchronous computation or request. Since JS has no native async capabilities (such as threads), callbacks are typically used to resume an operation asynchronously. The most important thing to realize is that you cannot return the result of an async computation or request, but must resume control flow after it completes. Defining lots of functions can help make this kind of code easier to read and understand.
This example illustrates what's happening:
process.nextTick(function() {
console.log('second')
})
console.log('first')
That program will log first, then second, because process.nextTick() asynchronously invokes the callback function provided to it (on the next turn of the event loop).
The answers at How do I get started with Node.js offer lots of resources to better understand async programming with node.js.

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.

Function with mongodb find does not return result

I am trying to return a Mongo result when I call a function in Swig template. It does not wait for the mongo result and continues rendering the template.
Example code:
function swigfunction(){
db.collection('contentitems').find({}).toArray(function(err, docs) {
//generated my output
return myoutput;
});
}
Then I try to call the function, but "undefined" gets returned.
{{ swigfunction() }}
Please help
The MongoDB API uses an asynchronous callback mechanism. That means instead of just idling and wasting resources, the program will continue while the database processes your request. When the response from the database finally arrives, the callback function return myoutput; is executed.
The usual pattern in node.js is to nest all your asynchronous function calls and write the output in the innermost callback function.
You can use mongo-sync sync mongo-db client library.

How should mongoose's model.on('index', ...) be used?

In looking at the documentation for MongooseJS for MongoDB/Node.js, it appears that indexing may be specified on an object like so:
var MyModelSchema = new Schema({ name: String, index: true });
var MyModel = mongoose.model('MyModel', MyModelSchema);
MyModel.on('index', function()
{
doStuff();
});
Per the documentation, Mongoose will call ensureIndex() upon startup unless the "autoIndex" option is explicitly set to false on the schema. Once this is completed, the 'index' event will be emitted on the model, which would trigger the callback.
My understanding is that this allows a user of a model to ensure that all indexing has been completed prior to use of a model.
I believe I heard mention of doing this via app.configure, although I'm not sure how this could be done. Maybe there is another way to guarantee completion of this indexing operation prior to other parts of the application relying on the exported model?
How should this properly be used?
The 'index' event on your model is there to alert you to any errors that occurred in the model's ensureIndex calls. You don't need to delay use of the model until the event fires. That would get pretty messy.
I found it useful to add the following to the area used to configure the project's mongoose settings.
let mongoose = require('mongoose');
mongoose.Model.on('index', function(err) {
if (err) logger.error(err);
});

Resources