2013-08-21 53 views
2

我正在使用NodeJS的MongoDB本地驅動程序,並且在將ObjectID轉換爲string時遇到問題。NodeJS,使用MongoDB本地驅動程序,如何將ObjectID轉換爲字符串

我的代碼如下所示:

db.collection('user', function(err, collection) { 
    collection.insert(data, {safe:true}, function(err, result) { 
    var myid = result._id.toString(); 
    console.log(myid); 
)}; 
}); 

我曾嘗試在計算器上的各種建議,如:

myid = result._id.toString(); 
myid = result._id.toHexString(); 

但他們都不似乎工作。

我試圖將ObjectID轉換爲base64編碼。

不知道我是否在Mongo本機驅動程序下運行支持的功能。

回答

2

insert返回結果的數組(您也可以發送到插入對象的數組),那麼你的代碼試圖從陣列實例中獲取_id而不是第一個結果:

MongoClient.connect("mongodb://localhost:27017/testdb", function(err, db) { 
    db.collection("user").insert({name:'wiredprairie'}, function(err, result) { 
     if (result && result.length > 0) { 
      var myid = result[0]._id.toString(); 
      console.log(myid); 
     } 
    }); 
}); 

此外,您不需要base64編碼調用toStringObjectId上的結果,因爲它已經作爲十六進制數字返回。您也可以撥打:result[0]._id.toHexString()直接獲取十六進制值(toString只是包裝toHexString)。

+0

謝謝,很高興知道它爲什麼不起作用。 – Arcane

6

這項工作對我來說:

var ObjectID = require('mongodb').ObjectID; 
var idString = '4e4e1638c85e808431000003'; 
var idObj = new ObjectID(idString); 

console.log(idObj); 
console.log(idObj.toString()); 
console.log(idObj.toHexString()); 

輸出:

4e4e1638c85e808431000003 
4e4e1638c85e808431000003 
4e4e1638c85e808431000003 
+0

謝謝,這兩個例子都非常有幫助 – Arcane

相關問題