1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Mongoose 6 で meow

Posted at

認証エラーが出た

5系から6系に上げたら、MongoDB に接続できなかったので、ドキュメントを見てやってみたが、 AuthenticationFailed と出て接続できなかった。

解決策

?authSource=admin を付ける。

const mongoUrl = `mongodb://${user}:${password}@${host}:${port}/${dbname}?authSource=admin`;
mongoose.connect(mongoUrl);

猫がなくコード一式

docker-compose.yml
version: "3.1"

services:
  mongo:
    container_name: mongo-dev
    image: mongo
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: ${MONGO_USER}
      MONGO_INITDB_ROOT_PASSWORD: ${MONGO_PASS}
      MONGO_INITDB_DATABASE: ${MONGO_DBNAME}
    ports:
      - 27017:27017
    volumes:
      - ./configdb:/data/configdb
      - mongoStore:/data/db

volumes:
  mongoStore:
    driver: local
app.js
const mongoose = require('mongoose');

require('dotenv').config();
const mongoUrl = `mongodb://${process.env.MONGO_USER}:${process.env.MONGO_PASS}@localhost:27017/${process.env.MONGO_DBNAME}?authSource=admin`;

mongoose.connect(mongoUrl);

const Cat = mongoose.model('Cat', { name: String });

const kitty = new Cat({ name: 'Zildjian' });
kitty.save().then(() => console.log('meow'));
".env"
MONGO_USER=xxx
MONGO_PASS=xxx
MONGO_DBNAME=xxx
$ npm init
$ yarn install mongoose dotenv
$ node app.js
meow
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?