MongoDB Node JS Driver找到toArray以不同的格式获取Object Id

时间:2016-01-05 06:41:37

标签: node.js mongodb

我正在尝试从集合中获取所有文档,如下所示:

var server = "localhost";
var port   = 27017; 
var dbName = "myNewCreation";
var mongodb          = require('mongodb');
var mongoClient = mongodb.MongoClient;
var connString = "mongodb://"+server+":"+port+"/"+dbName;

mongoClient.connect(connString, function(err, db) {
    console.dir(err);
    if(!err) {
        var collectionName = "employee";
        //get Documents
        db.collection(collectionName).find({}).toArray(function (err, docs) {
          console.dir(err);
          console.dir(docs);
        });
    }
    else{
        console.log("Mongo DB could not be connected");
        process.exit(0);
    }

});

我正确地得到了结果,但对象ID的输出是某种机器格式,如下所示:

[ { _id: ObjectID { _bsontype: 'ObjectID', id: 'VX%\u000fÜÏ¢6©ø' },
    empName: 'riyke',
    Dob: '20-31-2300',
    salary: '7000' } ]

如何以人类可读的形式正确获取对象ID?

我找到了解决方案并且工作正常,我只是用答案更新我的问题:

使用toString或toHexString方法,如下所示:

var server = "localhost";
    var port   = 27017; 
    var dbName = "myNewCreation";
    var mongodb          = require('mongodb');
    var mongoClient = mongodb.MongoClient;
    var connString = "mongodb://"+server+":"+port+"/"+dbName;

    mongoClient.connect(connString, function(err, db) {
        console.dir(err);
        if(!err) {
            var collectionName = "employee";
            //get Documents
            db.collection(collectionName).find({}).toArray(function (err, docs) {
              console.dir(err);
              console.dir(docs);
              consolde.dir(docs[0]._id.toString());
              consolde.dir(docs[0]._id.toHexString());      
            });
        }
        else{
            console.log("Mongo DB could not be connected");
            process.exit(0);
        }

    });

1 个答案:

答案 0 :(得分:0)

您可以使用valueOf()方法,ObjectId.valueOf()它将返回十六进制字符串