node.js - 如何过滤 Mongoose changeStream

标签 node.js mongodb mongoose

我正在开发一个聊天系统,我尝试使用mongoDB/mongoose的changeStream。

我只想在当前用户是收件人的情况下获取文档,但它不起作用。到目前为止,我遇到过两个案例。一个永远不会触发,另一个会返回所有文档,即使当前用户不是收件人。

区别在于管道是否在数组中。

你知道什么是正确的语法吗?

<小时/>

我读了最近两天在google上找到的所有前10页的文章,但没有一篇包含如何过滤。据我了解,聚合管道仅用于操作结果,但不可能排除不通过条件的文档。

<小时/>

这是我所做的:

const pipeline = [{
     $match: { 
         "userId": this.recipient.id,
         "recipientId": this.user.id
    }
}]

const stream = MessageModel.watch(pipeline )

stream.on('change', (data: any) => {
    console.log(`messages changed`);
    this.socketIo.sockets.in(this.socket.id).emit(`protected/message/subscribe/${this.msg.msgId}`, data.fullDocument);
});

最佳答案

这可能有用

const { ReplSet } = require('mongodb-topology-manager');
const mongoose = require('mongoose');

run().catch(error => console.error(error));

async function run() {
  console.log(new Date(), 'start');
  const bind_ip = 'localhost';
  // Starts a 3-node replica set on ports 31000, 31001, 31002, replica set
  // name is "rs0".
  const replSet = new ReplSet('mongod', [
    { options: { port: 31000, dbpath: `${__dirname}/data/db/31000`, bind_ip } },
    { options: { port: 31001, dbpath: `${__dirname}/data/db/31001`, bind_ip } },
    { options: { port: 31002, dbpath: `${__dirname}/data/db/31002`, bind_ip } }
  ], { replSet: 'rs0' });

  // Initialize the replica set
  await replSet.purge();
  await replSet.start();
  console.log(new Date(), 'Replica set started...');

  // Connect to the replica set
  const uri = 'mongodb://localhost:31000,localhost:31001,localhost:31002/' +
    'test?replicaSet=rs0';
  await mongoose.connect(uri);

  // To work around "MongoError: cannot open $changeStream for non-existent
  // database: test" for this example
  await mongoose.connection.createCollection('people');

  const Person = mongoose.model('Person', new mongoose.Schema({ name: String }));

  // Create a change stream. The 'change' event gets emitted when there's a
  // change in the database
  Person.watch().
    on('change', data => console.log(new Date(), data));

  // Insert a doc, will trigger the change stream handler above
  console.log(new Date(), 'Inserting doc');
  await Person.create({ name: 'Axl Rose' });
  console.log(new Date(), 'Inserted doc');
}

关于node.js - 如何过滤 Mongoose changeStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57637479/

相关文章:

javascript - Node.js 中的 ENOMEM 由高虚拟内存使用率引起

node.js - Swagger UI 不发送 url 参数

mongodb - 所有产品的单一大集合与每个产品类别的单独集合

node.js - 执行 mongoose 聚合查询时 _id 字段出现奇怪字符

javascript - Mongoose 用 promise 保存并填充

node.js - Electron 应用程序的基本调试

node.js - 如何在不创建模型的情况下插入对模型的引用?

node.js - meteor 主机上的 meteor 部署错误

javascript - Node.js 类型错误 : undefined is not a function

javascript - Node.JS 可用于在安全的服务器端环境中验证许可证 key 吗?