1 Star 0 Fork 0

hcxiong/mongo-exprss-master

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
bson.js 2.18 KB
一键复制 编辑 原始数据 按行查看 历史
xiexiao04 提交于 2015-04-12 22:57 +08:00 . 本机已经配置完成
var mongodb = require('mongodb');
var vm = require('vm');
var json = require('./json');
//Adaptors for BSON types
var DBRef = function(namespace, oid, db) {
//Allow empty/undefined db value
if (db == undefined || db == null) {
db = '';
}
return mongodb.DBRef(namespace, oid, db);
}
var Timestamp = function(high, low) {
//Switch low/high bits to Timestamp constructor
return mongodb.Timestamp(low, high);
}
//Create sandbox with BSON data types
exports.getSandbox = function() {
return {
Long: mongodb.Long,
NumberLong: mongodb.Long,
Double: mongodb.Double,
NumberDouble: mongodb.Double,
ObjectId: mongodb.ObjectID,
ObjectID: mongodb.ObjectID,
Timestamp: Timestamp,
DBRef: DBRef,
Dbref: DBRef,
Binary: mongodb.Binary,
BinData: mongodb.Binary,
Code: mongodb.Code,
Symbol: mongodb.Symbol,
MinKey: mongodb.MinKey,
MaxKey: mongodb.MaxKey,
ISODate: Date,
Date: Date
};
};
//JSON.parse doesn't support BSON data types
//Document is evaluated in a vm in order to support BSON data types
//Sandbox contains BSON data type functions from node-mongodb-native
exports.toBSON = function(string) {
var sandbox = exports.getSandbox();
string = string.replace(/ISODate\(/g, "new ISODate(");
vm.runInNewContext('doc = eval((' + string + '));', sandbox);
return sandbox.doc;
};
// Converts string to ObjectID. TODO: Add validation.
exports.toObjectId = function(string){
var sandbox = exports.getSandbox();
// Strip quotes
string = string.replace('"', '').replace('"', '');
// Convert ObjectId("526ddf5a9f610ffd26000001") to 526ddf5a9f610ffd26000001
string = string.replace(/ObjectID\(/i, '').replace(')', '');
// Make sure it's a 24-character string to prevent errors.
if (string.length == 24) {
return sandbox.ObjectID(string);
} else {
return false;
}
}
//Convert BSON documents to string
exports.toString = function(doc) {
//Use custom json stringify function from json.js
return json.stringify(doc, null, ' ');
};
exports.toJsonString = function(doc) {
var sJson = json.stringify(doc, null);
sJson = sJson.replace(/ObjectID\(/g, '{ "$oid": ');
sJson = sJson.replace(/\)/g, ' }');
return sJson;
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/hcxiong/mongo-exprss-master.git
git@gitee.com:hcxiong/mongo-exprss-master.git
hcxiong
mongo-exprss-master
mongo-exprss-master
master

搜索帮助