我正在尝试查找一个我知道存在的文档,因为多亏了mongo-express,我可以在管理控制台中看到它。但是,当我使用Model.findOne(
时,它会出现以下错误消息。我究竟做错了什么? (主机名“ mongo”是我的docker容器,它连接得很好,我可以在日志中看到它)
这是我的代码:
// 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: incommingId }, ( error, x ) => {
//handler
})
我最终遇到这个错误
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)
答案 0 :(得分:-2)
答案简单而愚蠢。上面的所有内容都是正确的...保留未定义的环境变量。
显然mongo可以让您未经授权而连接,您什么也做不了。正确地填充这些环境变量,一切都可以顺利进行。