【问题标题】:Connect to existing MongoDB with a new node express server使用新的节点快速服务器连接到现有 MongoDB
【发布时间】:2021-04-14 14:42:54
【问题描述】:

我有一个使用 mongoose 连接到 MongoDB 的现有节点/express 服务器。一切正常。

我想创建一个单独的节点/快递服务器来运行 cron 作业(发送电子邮件、推送通知等)

首先,这是一个好的实现吗? (我查看过 RabbitMQ 之类的消息队列,但对于我需要的东西似乎有点矫枉过正。)

其次,我很难将我的第二个节点/express 应用程序连接到现有的 MongoDB。我尝试过与 mongoose 以及直接与 mongodb 连接,但运气不佳。

这是我尝试过的众多方法之一的示例:

const client = new MongoClient(keys.mongoURI, { useUnifiedTopology: true });

async function run() {
  try {
    // Connect the client to the server
    const db = await client.connect();
    // Establish and verify connection
    await client.db("my-db").command({ ping: 1 });
    console.log("Connected successfully to server");

    const users = await db.users.find()
    await console.log(users)

  } finally {
    // Ensures that the client will close when you finish/error
    await client.close();
  }
}

我收到find is not a function

任何指针?

【问题讨论】:

  • 您是否连接到同一个数据库?您可以连接,因此连接似乎不是问题,在这种情况下,check the collections 可用于检查您要连接的数据库中是否确实存在user
  • 你正在运行 2 个不同的操作,data = await db("dbHere").users.find().toArray(); console.log(data)
  • @luckongas 变暖了!我可以通过您的建议查看收藏。但是我如何获得对集合的引用?我尝试将.listCollections().find() 交换,但没有奏效。 @Minsky 谢谢你的帮助。那没用,我得到“db is not a function”
  • 你用的是mongodb驱动还是猫鼬?

标签: node.js mongodb express mongoose


【解决方案1】:

对于 MongoDB 驱动程序,这应该可以工作:

const client = new MongoClient(keys.mongoURI, { useUnifiedTopology: true });

async function run() {
  try {
    // Connect the client to the server
    const db = await client.connect();
    // Establish and verify connection
    await client.db("my-db").command({ ping: 1 });
    console.log("Connected successfully to server");

    const users = await db("my-db").collection("users").find();
    console.log(users);

  } finally {
    // Ensures that the client will close when you finish/error
    await client.close();
  }
}

虽然对于猫鼬,这种方法应该有效:

// You have your mongoose connection to the database and then
async function run() {
  try {
    ... you connect to your database and ping it ...

    const users = await mongoose.connection.db.collection("users").find();
    console.log(users);

  } finally {
    // Ensures that the client will close when you finish/error
    await client.close();
  }
}

如果您发现任何其他问题,请告诉我

【讨论】:

    猜你喜欢
    • 2019-12-24
    • 1970-01-01
    • 2021-01-28
    • 2022-11-15
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    • 2023-03-29
    相关资源
    最近更新 更多