node.js - Node JS 中 MongoDB 对象 ID 的 BSON/二进制到字符串

标签 node.js mongodb

我正在研究 MongoDB 版本 3.6 中引入的变更流。更改流有一个功能,我可以指定从历史记录中的特定更改开始流式传输更改。在 Node.js 的 native 驱动程序中,要恢复更改流,它会显示 ( documentation here )

Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document.

当我在控制台中打印它时,这就是我得到的

{ _id: 
   { _data: 
      Binary {
        _bsontype: 'Binary',
        sub_type: 0,
        position: 49,
        buffer: <Buffer 82 5a 61 a5 4f 00 00 00 01 46 64 5f 69 64 00 64 5a 61 a5 4f 08 c2 95 31 d0 48 a8 2e 00 5a 10 04 7c c9 60 de de 18 48 94 87 3f 37 63 08 da bb 78 04> } },
        ...
}

我的问题是我不知道如何将这种格式的_id存储在数据库或文件中。是否可以将此二进制对象转换为字符串,以便我稍后可以使用它从该特定 _id 恢复我的更改流。示例代码将不胜感激。

最佳答案

将 BSON 二进制转换为缓冲区并返回

const Binary = require('mongodb').Binary;
const fs     = require('fs');

从_id保存_data:

var wstream = fs.createWriteStream('/tmp/test');
wstream.write(lastChange._id._data.read(0));
wstream.close();

然后重建resumeToken:

fs.readFile('/tmp/test', void 0, function(err, data) {
  const resumeToken = { _data: new Binary(data) };
});

关于node.js - Node JS 中 MongoDB 对象 ID 的 BSON/二进制到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48338484/

相关文章:

java - 添加第二个 '$or' 表达式失败

mongodb - 如何使用 --auth 选项运行 flapdoodle MongodStarter

node.js - 在 conda 环境中安装 nodeJS

mongodb - 服务运行时无法连接到mongodb,raspbian

node.js - 如何在采取进一步行动之前等待 Sequelize 结果?

node.js - Node http 请求无序执行,导致使用随机数值的 API 出现问题

python - 处理 MongoDB 和 pymongo 中的时区日期

node.js - MongoDB GridFS API 返回损坏的 .zip

javascript - setAttribute ('display' ,'block' )不工作 selenium-webdriver Node js

node.js - 如何从数据库中删除环回模型和引用