2016-11-03 55 views
0

我是Node.js和MongoDB的新手,我真的很努力地繞過回調。我已經閱讀了一些文章,但對我來說仍然很困惑。在下面的代碼,我試圖返回orders計有,我已經在orderModel.count(query, next)表示對查詢的一些特性:Node.js - 計算MongoDB集合中的對象數

控制器/ 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}); 
} 

我不認爲我正確地獲取變量count,因爲當我試圖打印出的if語句中的第二條件的結果,我得到這個數據打印出來:

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 } }, 
.... 

回答

1

你需要把你的日誌IC的Model.count()方法回調函數作爲內:

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 }); 
     }   
    }) 
} 
+1

是的,這就是我一直會錯。謝謝! – SalmaFG