mongodb fastify + mongo =为什么数据库中没有存储任何内容?

myzjeezk  于 2023-01-25  发布在  Go
关注(0)|答案(1)|浏览(160)

我正在用mongodb构建一个fastify应用程序,我创建了这个package.json文件,其中包含运行mongo的脚本。

{
    "dependencies": {
        "@fastify/mongodb": "5.0.0",
        "fastify": "4.11.0"
    },
    "scripts": {
        "start": "node server.js",
        "start-mongo": "docker run -d --name my-mongo -p 27017:27017 mongo",
    }
}

使用npm run start-mongo,我运行mongo暴露端口27017。然后,...这是fastify部分。

const fastify = require('fastify')({logger: true})

fastify.register(require('@fastify/mongodb'), {
    forceClose: true,
    url: 'mongodb://localhost:27017/library'
})

fastify.get('/books', async(request, reply) => {
    const books = await fastify.mongo.db
        .collection('books')
        .find()

    reply.send(books)
});

fastify.post('/books', async(request, reply) => {
    const result = await fastify
        .mongo.db
        .collection('books')
        .insertOne(request.body)

    reply.send({
        message: 'book added',
        id: result.insertId
    })
})

GET/书籍:

{"_events":{},"_eventsCount":0}

邮政/书籍

curl -H 'Content-Type: application/json' -X POST http://localhost:3000/books -d '{"message":"prova"}'

退货

{"message":"book added"}

这很奇怪,因为响应应该也包含id,但它没有。

reply.send({
        message: 'book added',
        id: result.insertId
    })

这意味着

const result = await fastify
        .mongo.db
        .collection('books')
        .insertOne(request.body)

不存储图书。显示任何错误,GET始终返回:

{"_events":{},"_eventsCount":0}

怎么啦?

我还用docker-compose创建了mongo:

version: '3.1'
services:
  mongo:
    image: mongo
    restart: always
    ports:
      - 27017:27017
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example

但它返回:

{
  statusCode: 500,
  code: '13',
  error: 'Internal Server Error',
  message: 'command insert requires authentication'
}
{
  statusCode: 500,
  code: '13',
  error: 'Internal Server Error',
  message: 'command find requires authentication'
}

我从更新了代码

fastify.register(require('@fastify/mongodb'), {
    forceClose: true,
    url: 'mongodb://localhost:27017/library'
})

fastify.register(require('@fastify/mongodb'), {
    forceClose: true,
    url: 'mongodb://root:example@localhost:27017/library'
})

但返回:

(node:86146) UnhandledPromiseRejectionWarning: MongoServerError: Authentication failed.
    at Connection.onMessage (/Users/simonegentili/Development/github.com/sensorario/youtube.poliglotta/node_modules/mongodb/lib/cmap/connection.js:227:30)
    at MessageStream.<anonymous> (/Users/simonegentili/Development/github.com/sensorario/youtube.poliglotta/node_modules/mongodb/lib/cmap/connection.js:60:60)
    at MessageStream.emit (events.js:375:28)
    at processIncomingData (/Users/simonegentili/Development/github.com/sensorario/youtube.poliglotta/node_modules/mongodb/lib/cmap/message_stream.js:125:16)
    at MessageStream._write (/Users/simonegentili/Development/github.com/sensorario/youtube.poliglotta/node_modules/mongodb/lib/cmap/message_stream.js:33:9)
    at writeOrBuffer (internal/streams/writable.js:358:12)
    at MessageStream.Writable.write (internal/streams/writable.js:303:10)
    at Socket.ondata (internal/streams/readable.js:726:22)
    at Socket.emit (events.js:375:28)
    at addChunk (internal/streams/readable.js:290:12)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:86146) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:86146) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

为什么"认证失败"?

t98cgbkg

t98cgbkg1#

您需要:
1.更新fastify mongo to v6以支持fastify v4

  1. GET返回一个游标,因此将其更改为fastify.mongo.db.collection('books').find().toArray()
    1.要恢复插入的ID,您需要从inserted更改为insertedId
    1.要设置MongoDB密码duplicated question,或者需要设置database属性-更新了以下代码:
  • 注意插件配置
  • 注意fastify.mongo.db.collection的用法

快速和肮脏的复制粘贴:

const fastify = require('fastify')({ logger: !true })

fastify.register(require('@fastify/mongodb'), {
  forceClose: true,
  url: 'mongodb://root:example@localhost:27017',
  database: 'library'
})

fastify.get('/books', async (request, reply) => {
  const books = await fastify.mongo.db.collection('books').find().toArray()

  reply.send(books)
})

fastify.post('/books', async (request, reply) => {
  const result = await fastify
    .mongo.db
    .collection('books')
    .insertOne(request.body)

  reply.send({
    message: 'book added',
    id: result.insertedId
  })
})

async function start () {
  const done = await fastify.inject({
    method: 'POST',
    url: '/books',
    body: { asd: 'foo' }
  })
  console.log(done.json())

  const res = await fastify.inject('/books')
  console.log(res.json())

  fastify.close()
}

start()

相关问题