SalmaFG SalmaFG - 1 month ago 5
Node.js Question

Node.js - Counting the number of objects in MongoDB collection

I am new to Node.js and MongoDB and I am really struggling to wrap my head around callbacks. I have read a few articles but it is still quite confusing to me. In the code below, I am trying to return the count of

orders
that have some properties which I have expressed in the query in
orderModel.count(query, next)
:

controllers/order.js:

var mongoose = require ('../config/db');
var orderModel = require('../models/order').model;
var User = require('./user');
var Error = require('../config/error');
createOrder: function (user, order, next) {
if (newOrder.totalPrice > user.credit && orderModel.
count({$and: [{user: order.user}, {active: true}, {$or: [{status: 0}, {status: 1}]}]},
function(err, count){
if(err)
console.log(err);
else
count; }) > 0)
return next({error: Error.InsufficientCredits});
}


I don't think I am correctly obtaining the variable
count
because when I tried printing out the result of the second condition in the
if
statement, I got this data printed out:

Query {
_mongooseOptions: {},


mongooseCollection:
NativeCollection {
collection: Collection { s: [Object] },
opts: { bufferCommands: true, capped: false },
name: 'orders',
collectionName: 'orders',
conn:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: 'dsXXXXXX.mlab.com',
port: XXXXXX,
user: 'XXXX',
pass: 'XXXX',
name: 'X',
options: [Object],
otherDbs: [],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
_listening: false,
db: [Object],
_events: {},
_eventsCount: 0 },
queue: [],
buffer: false,
emitter:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined } },
....

Answer

You need to put your logic inside the Model.count() method callback function as:

var mongoose = require ('../config/db'),
    orderModel = require('../models/order').model,
    User = require('./user'),
    Error = require('../config/error');

var createOrder = function (user, order, next) {
    orderModel.count({
        "user": order.user, 
        "active": true, 
        "status": { "$in": [0, 1] }
    }, function(err, count) { //<-- put logic in this callback
        if (err) {
            console.log(err);
            throw err;
        } else if (newOrder.totalPrice > user.credit && count > 0) {
            // logic for creating order here
        } else {
            return next({ "error": Error.InsufficientCredits });
        }        
    })
}