SalmaFG SalmaFG - 9 months ago 62
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

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


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 > && orderModel.
count({$and: [{user: order.user}, {active: true}, {$or: [{status: 0}, {status: 1}]}]},
function(err, count){
count; }) > 0)
return next({error: Error.InsufficientCredits});

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

Query {
_mongooseOptions: {},

NativeCollection {
collection: Collection { s: [Object] },
opts: { bufferCommands: true, capped: false },
name: 'orders',
collectionName: 'orders',
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: '',
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,
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined } },

Answer Source

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) {
        "user": order.user, 
        "active": true, 
        "status": { "$in": [0, 1] }
    }, function(err, count) { //<-- put logic in this callback
        if (err) {
            throw err;
        } else if (newOrder.totalPrice > && count > 0) {
            // logic for creating order here
        } else {
            return next({ "error": Error.InsufficientCredits });