2016-12-15 26 views
0

我想根據學生身份證獲得記錄,然後按照以下方法進行操作,但即使數據存在,我也可以使用該方法獲取空白。 我在DB數據,如何通過對象身份證在貓鼬身上獲得記錄

{ 
"_id" : ObjectId("58526f02b7258b0ec168ee77"), 
"student" : ObjectId("58525c4c8cdabb7841b68163"), 
"updated" : null, 
"record_type" : "Invoice", 
"created" : ISODate("2016-12-15T10:22:58.801Z"), 
"__v" : 0 

}

我的查詢,

exports.searchInvoiceByStudent = function (req, res) { 
    var data = {}, 
    id = req.params.id, 
    item = {'record_type':'Invoice','student':id}; 
    Invoice.find(item).exec(function (err, invoice) { 
    if (err) { 
    return err; 
    } 
    if (invoice.length > 0) { 
    data = { status: 'success', error_code: 0, data: invoice }; 
    } else { 
    data = { status: 'fail', error_code: 1, data: invoice }; 
    } 
    res.jsonp({ 'details': invoice }); 
    }); 
}; 

但我得到一個空數組,可以在任何一個請建議help.Thanks。

+0

您可以編輯您的問題,包括對'Invoice'架構定義? – JohnnyHK

回答

0

你可以使用這樣的事情:

exports.searchInvoiceByStudent = function (req, res) { 
    var data = {}, 
    id = req.params.id, 
    item = {'record_type':'Invoice','student':id}; 
    Invoice.find({student : id, record_type: 'Invoice}, function (err, invoice) { 
    if (err) { 
    return err; 
    } 
    if (invoice.length > 0) { 
    data = { status: 'success', error_code: 0, data: invoice }; 
    } else { 
    data = { status: 'fail', error_code: 1, data: invoice }; 
    } 
    res.jsonp({ 'details': invoice }); 
    }); 

該版本採用直接回調(而不是執行)。

或者,如果您喜歡承諾(承諾由exec返回),您必須使用Promise#addBack(listener)添加您的查詢結果偵聽器,這在代碼示例中缺少。

貓鼬文檔提到這個例子(爲許諾,情況):

// using the promise returned from executing a query 
var query = MyModel.find({ name: /john/i }, null, { skip: 10 }); 
var promise = query.exec(); 
promise.addBack(function (err, docs) {}); 
相關問題