mongodb Mongoose watch()未触发插入事件

68de4m5k  于 2023-03-07  发布在  Go
关注(0)|答案(1)|浏览(174)

mongodb的当前版本是4.4.6,Data.watch()方法没有触发器。我检查了changeStream,创建的连接很好,没有问题。流也正确创建。我尝试通过我的API和mongodb客户端添加数据。

const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const mongoose = require('mongoose');
app.use(express.json())

// Connect to MongoDB using Mongoose
mongoose.connect('mongodb://localhost:27017/socketdb');

// Define a schema for the data
const dataSchema = new mongoose.Schema({
  name: String,
  age: Number,
  timestamp: { type: Date, default: Date.now }
});

// Create a model for the data
const Data = mongoose.model('Data', dataSchema);

// Connect to Socket.io
io.on('connection', function (socket) {
  console.log('A user connected');
  Data.find({}).then(
    data => socket.emit('allData', data)
  ).catch(err => console.log(err))

  // Watch for changes in the MongoDB collection
  if (mongoose.connection.readyState !== 1) {
    console.log('Mongoose is not connected');
  }
  let pipeline = [
    {
      $match: {
        operationType: 'insert'
      }
    }
  ];
  
  let changeStream = Data.watch(pipeline)
  .on('change', data => console.log(data))

  console.log(changeStream)
  changeStream.on('change', function (change) {
    console.log('Change stream event:', change);

    // Send the new or updated data to the client
    if (change.operationType === 'insert') {
      socket.emit('newData', change.fullDocument);
      console.log(change.fullDocument)
    } else if (change.operationType === 'update') {
      Data.findById(change.documentKey._id, function (err, data) {
        if (err) throw err;
        socket.emit('newData', data);
      });
    }
  });

  socket.on('disconnect', function () {
    console.log('A user disconnected');
    // changeStream.close();
  });
});

// Serve the HTML page
app.get('/', function (req, res) {
  res.sendFile(__dirname + '/index.html');
});

app.post('/adddata', (req, res) => {
  let d = new Data({
    name: req.body.name,
    age: req.body.age
  })
  d.save().then(() => {
    res.send("Data Added")
  }).catch((err) => {
    res.send("ERR")
  })
  Data.watch(pipeline).on('change', data => console.log('inside the add',data))

})

// Start the server
http.listen(3000, function () {
  console.log('Listening on port 3000');
});

这里changeStream.on('change')从来没有得到触发器,即使数据被添加。我从以下官方文档跟踪:Official Documentation

3mpgtkmj

3mpgtkmj1#

这个问题是因为你使用的是本地数据库,使用一个共享集群,然后它会工作。
注意:您必须连接到MongoDB副本集或分片集群才能使用变更流。Mongoose Documentation
您可以通过访问MongoDB Atlas. MongoDB Atlas创建一个
1.在Atlas上创建账户
1.创建一个共享群集(您可以免费创建一个)。
1.从应用程序连接到群集。How to connect to your cluster

相关问题