首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何过滤猫鼬changeStream

如何过滤猫鼬changeStream
EN

Stack Overflow用户
提问于 2019-08-24 11:21:09
回答 1查看 1.2K关注 0票数 4

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

我只希望在当前用户是收件人的情况下获得文档,但它不起作用。到目前为止,我已经遇到了两起案件。一个不触发,另一个与所有文档一起返回,即使不是当前用户是收件人。

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

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

在过去的两天里,我在google的头10页上看到了所有的文章,但是没有一篇文章包含如何过滤。据我所知,聚合管道仅用于操作结果,但不可能排除不传递条件的文档。

以下是我所做的:

代码语言:javascript
复制
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);
});
EN

回答 1

Stack Overflow用户

发布于 2019-08-24 11:48:07

这可能是有用的

代码语言:javascript
复制
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');
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57637479

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档