我浏览了this明示教程。我想知道是否可以将以下调用外包给单独的函数,因为它非常非常长?
employee_collection.db.bson_serializer.ObjectID.createFromHexString(id)
这是调用该语句的整个文件:
var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSON;
var ObjectID = require('mongodb').ObjectID;
EmployeeProvider = function(host, port) {
this.db = new Db(
'node-mongo-employee',
new Server(host, port, {}),
{safe: true}
);
this.db.open(function(){});
};
...
// find an employee by id
EmployeeProvider.prototype.findById = function(id, callback) {
this.getCollection(
function(error, employee_collection) {
if( error )
callback(error)
else {
employee_collection.findOne(
{_id: employee_collection.db.bson_serializer.ObjectID.createFromHexString(id)},
function(error, result) {
if( error )
callback(error)
else
callback(null, result)
}
);
}
}
);
};
...
exports.EmployeeProvider = EmployeeProvider;
它是一个 Express 应用程序的 Controller 。它被缩短了,但应该让您了解它的作用。您可以在 Github 上找到整个应用程序.
我试过了
getid = function( employee_collection, id ) {
return employee_collection.db.bson_serializer.ObjectID.createFromHexString(id);
};
并调用该函数
{_id: getid(employee_collection, id),
但是我遇到了一个很长的 ENOENT 错误。
最佳答案
假设您正在使用基本的node.js mongodb驱动程序,并且您的id
本质上是作为请求参数之类的东西进来的,这意味着它只是一个字符串,看起来像这样:
"53cfba87e248860d16e1f7e1"
然后是您在此处使用的导入:
var ObjectID = require('mongodb').ObjectID;
为您提供直接使用的功能。只需这样做:
employee_collection.findOne({ "_id": ObejctID(id) },function(err,result) {
// work in here
});
您导入的ObjectID
已经实现了此功能。
关于javascript - 将 XXX.db.bson_serializer.ObjectID.createFromHexString(id) 外包给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24911704/