I'm trying to find a document I know exists because I can see it in the admin console thanks to mongo-express... however when I use Model.findOne(
it vomits the below error message. WHAT am I doing wrong? ( the hostname 'mongo' is my docker container, and it connects just fine, I can see it in the logs )
This my code:
// This all works because the following events show success, and no error.
// So I know it's authing correctly on initial connection
-dbConnect.js-
"user strict"
import mongoose from "mongoose"
const connection = mongoose.createConnection(
"mongodb://mongo:27017/dbName?authSource=admin", {
useNewUrlParser: true,
user: process.env.user,
pass: process.env.pass,
keepAlive: true,
})
connection.on( "connected", () => {
console.log( "MONGOOSE: connected" )
})
connection.on( "close", () => {
console.log( "MONGOOSE: connection close" )
})
connection.on( "error", error => {
console.log( "MONGOOSE: connection error", error )
})
export default connection
-models/auth.js-
"use strict"
import mongoose from "mongoose"
import connection from "../dbConnect"
const xSchema = new mongoose.Schema(
{
id : String,
user : String,
pass : String
},
{ collection: "x" }
)
export const X = connection.model( "X", xSchema )
-controllers/auth.js-
import { X } from "../models/auth"
//Promise wrapper
X.findOne( { id: incomingId }, ( error, x ) => {
//handler
})
And I end up with this error
MongoError: command find requires authentication
at Connection.<anonymous> (/usr/src/app/node_modules/mongodb-core/lib/connection/pool.js:443:61)
at Connection.emit (events.js:189:13)
at Connection.EventEmitter.emit (domain.js:441:20)
at processMessage (/usr/src/app/node_modules/mongodb-core/lib/connection/connection.js:364:10)
at Socket.<anonymous> (/usr/src/app/node_modules/mongodb-core/lib/connection/connection.js:533:15)
at Socket.emit (events.js:189:13)
at Socket.EventEmitter.emit (domain.js:441:20)
at addChunk (_stream_readable.js:284:12)
at readableAddChunk (_stream_readable.js:265:11)
at Socket.Readable.push (_stream_readable.js:220:10)
at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
Answer was simple and stupid. Everything above is correct... leave for the environment variables being undefined.
Apparently mongo lets you connect without being authorized, you just can't do anything. Filling those env vars correctly everything moved along perfectly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With