2016-05-12 89 views
-1

我正在使用nodejs + express和mongodb。Node + Mongodb + ObjectId不工作

我正在使用郵遞員並訪問API。 當我使用ObjectId服務器沒有響應任何東西。如果我刪除意味着運作良好。 我無法解決此問題。請任何人都可以幫忙。

test.js

//Post Data: 
{ 
    "list_id": "56963e4dbcd5d4ff27ced0fbd" 
} 


var app = require('express'); 
var router = app.Router(); 
var server = require('./../../server'); 
var mongoUtil = require('./../../mongoUtil'); 
var ObjectId = require('mongodb').ObjectID; 

router.post('/share', function(req, res, next) { 

    var data = { 
     query : {} 
    }; 
    console.log(req.body['list_id']); 
    //printed 56963e4dbcd5d4ff27ced0fbd 

    console.log(data.query); 
    //printed {} 

    data.query = ObjectId(req.body['list_id']); 
    console.log(data.query); 
    //Here not getting any response 
    // this line not printed and server no response. 
    //Also tried the following things. but its not working. 
    // data.query['_id'] = new ObjectID(req.body['list_id']); 
    //data.query._id = ObjectId(req.body['list_id']); 

    var collection = mongoUtil.list; 
    collection.findOne(data.query, function(err, list) { 
     console.log(err); 
     console.log(list); 
     if (!err && list) { 
      res.send("Sucess"); 
      return; 
     } else { 
      res.send("Error"); 
      return; 
     } 
    }); 

}); 
+0

包含ObjectID時會出現什麼錯誤? – Venky

+0

我沒有得到任何錯誤。服務器沒有響應。 – RSKMR

+0

'ObjectId()'構造函數需要一個24字節的十六進制字符串,12字節的二進制字符串或一個數字作爲它的參數,然而'req.body ['list_id']'只是一個普通的字符串。 – chridam

回答

1

56963e4dbcd5d4ff27ced0fbd應該是長度24,但它是25.請確保它是24.可能的工作。

ObjectID() 
Constructor 
Create a new ObjectID instance 

class ObjectID() 
Arguments: 
id (string) – Can be a 24 byte hex string, 12 byte binary string or a Number. 
Returns:  
object instance of ObjectID 
+0

我試過這個也不行 – RSKMR

+0

FWIW,你不需要'new'。 – robertklep

+0

@RSKMR編輯了我的答案。試一試。 – Venky