如何使用 Mongoose 驱动程序在 NestJS 应用程序中实现 MongoDB 更改流?

问题描述 投票:0回答:1

我有两个应用程序,一个是用 NestJS 构建的,另一个是用 Express 构建的。两者都连接到 MongoDB Atlas,并且我有一个用户表,只有一列:名称。我正在尝试使用 MongoDB 更改流在此表上实现实时更新。

快速申请


main()
  .catch((err) => console.log(err))
  .then(() => console.log('Connected to MongoDB'));
async function main() {
  await mongoose.connect(mongoDB);
}

app.get('/', async (req, res) => {
  await userMOdel.SomeModel.create({ name: 'Mohmad' });
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

快速用户架构


// Require Mongoose
const mongoose = require('mongoose');

// Define a schema
const Schema = mongoose.Schema;

const userSchema = new Schema({
  name: String,
});

const SomeModel = mongoose.model('users', userSchema);

const changeStream = SomeModel.watch();

changeStream.on('change', (change) => {
  console.log('Mongodb Change===============');
});

module.exports = {
  SomeModel,
};

Nestjs 应用程序


@Schema()
export class User {
    @Prop({
        type: String,
    })
    name: string;
}

export const UserSchema = SchemaFactory.createForClass(User);

@Injectable()
export class ChangeStreamService implements OnModuleInit {
    constructor(
        @InjectModel(User.name)
        private readonly userModel: Model<typeof User & Document>,
        @InjectConnection() private connection: Connection,
    ) {}

    // onModuleInit() {
    //     const changeStream = this.userModel.watch();
    //     changeStream.on('change', (change) => {
    //         console.log('Change:', change);
    //     });

    //     changeStream.on('error', (change) => {
    //         console.log('Error:', change);
    //     });
    // }

    onModuleInit() {
        this.connection.db
            .collection('users')
            .watch()
            .on('change', (change) => {
                console.log('Change:', change);
            });
    }
}

在模块内部我已经像这样导入了

 MongooseModule.forFeature([ {
                name: User.name,
                schema: UserSchema,
            }]

provider of same module 
 providers: [
       
        ChangeStreamService,
    ],

现在,在 Express 应用程序中,我已经成功实现了更改流功能,并且可以侦听对数据库所做的更改。然而,在 NestJS 应用程序中,我遇到了困难。尽管使用了 Mongoose 驱动程序,但我没有收到任何更新。

有人可以指导如何使用 Mongoose 驱动程序在 NestJS 应用程序中正确实现 MongoDB 更改流吗?任何代码示例或解释将不胜感激。

node.js mongodb mongoose nestjs typeorm
1个回答
0
投票

我的案例是这样的,并且成功了

 const changeStream = this.actuatorDeviceModel.watch();
    changeStream.on('change', (cb) => console.log('data', cb.fullDocument)); //return newest data
    
© www.soinside.com 2019 - 2024. All rights reserved.