#Global Modules

1 messages · Page 1 of 1 (latest)

candid oar
#

Hello im trying to use Global Modules but i get this error ```js
[Nest] 69499 - 07/18/2023, 10:57:37 PM ERROR [ExceptionHandler] Nest can't resolve dependencies of the AuthService (?). Please make sure that the argument Model at index [0] is available in the AuthModule context.

Potential solutions:

  • If Model is a provider, is it part of the current AuthModule?
  • If Model is exported from a separate @Module, is that module imported within AuthModule?
    @Module({
    imports: [ /* the Module containing Model */ ]
    })

Error: Nest can't resolve dependencies of the AuthService (?). Please make sure that the argument Model at index [0] is available in the AuthModule context. this is my app.modulejs
import { Global, Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { AuthService } from './auth/auth.service';
import { AuthModule } from './auth/auth.module';
import { User } from './app_modules/schemas/user.schema';
import { Menu } from './app_modules/schemas/menu.schama';

@Global()
@Module({
imports: [
MongooseModule.forRoot('mongodb://localhost:27017/nest'),
AuthModule,
User,
Menu,
],
providers: [AuthService, User, Menu],
exports: [AuthService],
})
export class AppModule {}
and this my auth.module.tsjs
import { Global, Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';

@Global()
@Module({
exports: [AuthService],
providers: [AuthService],
controllers: [AuthController],
})
export class AuthModule {}

tough bough
#

Please show your AuthService

candid oar
#
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { User } from 'src/app_modules/schemas/user.schema';

@Injectable()
export class AuthService {
  constructor(private userModel: Model<User>) {}
}

tough bough
#

How are you expecting Nest to know what to inject for the Model<User>? You need to use MongooseModule.forFeature([{ name: 'User', schenma: UserSchema }]) to set up the injection token and @InjectModel('User') to actually inject it

candid oar
#

so like this ```js
@Global()
@Module({
imports: [
MongooseModule.forFeature([{ name: 'User', schema: User }]),
AuthModule,
User,
Menu,
UserModule,
MenuModule,
],
providers: [AuthService, User, Menu, UserService],
exports: [AuthService],
controllers: [UserController],
})
export class AppModule {}

tough bough
#

Piece of advice, do not use your root module as a global holder for everything. You're gonna run into a lot of problems that way

#

Also, don't add services to more than oneproviders array, unless you want new instances in every module where you do it.

candid oar
#

so what should i change in my MongooseModule.forFeature so that it works

tough bough
#

Your root module should import MongooseModule.forRoot(). Your feature modules hsould import MongooseModule.forFeatuer()

candid oar
#

but i just have one forFeatuer in my app.module

tough bough
#

Right, and I'm saying you probably shouldn't. Your AppModule is your root module, correct? What gets passed to NestFactory.create()? That should hold global modules likeMongooseMoudle.forRoot() and it should import feature modules like UserModule and AuthModule to make Nest aware of them. For things like MongooseModule.forFeature(), you should import those inside your feature modules, so they are localized to the feature and not exposed elsewhere

candid oar
#

im very new with nestjs that why i dont understand very much

#

i dont understand how i can fix my problem now

tough bough
#

Then tell me what you don't understand. Don't just ask where to put the code to make it work, ask questions that guides you to knowing why the solution is what it is

candid oar
#

my question is if i should use in my app.module forFeature() and if yes for what

tough bough
#

I've already answered that too. In your root module (AppModule) you should import modules thast have a global configurastion (commonly seen as a forRoot) and feature modules (like UserModule and AuthModule).

In your feature modules is where you should add the MongooseModule.forFeature imports

candid oar
#

yeah and in which file should i make the MongooseModule.forFeature

tough bough
#

What that forFeature import is doing, is setting up an injection token to match the one retrieved by @InjectModel() so that when you're injecting your mongoose modules, Nest knows what you're trying to do

tough bough
candid oar
tough bough
#

I don't know how to make this any clearer: Use MongooseModule.forFeature in feature modules, not your root module

candid oar
#

where is the feature module???

tough bough
#

Not the feature module. A feature module.

#

A feature module is a feature of your application, like UserModule or AuthModule

candid oar
#

so i should create a feature module ? and there is my mongodb connection

tough bough
#

It is a, close to, self contained chunk of code, that can contain an entry point (controller, resolver, gateway), a private API (non-exported providers), a public API (exported providers) and a way to bring in other features (module imports)

candid oar
#

so what should i now do to fix my problem ?

tough bough
#

That's exactly what I told you not to ask

candid oar
#

yes but otherwise I do not know how to get further

tough bough
#

If I just write out the solution you'll have the same problem down the road. Try to re-read and understand what I've said so far, and ask for clarification on topics or terms you don't understand

candid oar
#

i will try it but i dont understand so manyyyy things

tough bough
#

Then ask specifically

candid oar
#

for example i dont understand this MongooseModule.forRoot([{ name: 'User', schema: User }]),

#

why should i do this js MongooseModule.forRoot([{ name: 'User', schema: User }]), and not this ```js
MongooseModule.forRoot('mongodb://localhost:27017/nest'),

tough bough
#

And this is all written out in our documentation too

candid oar
#

yes but the first example is this imports: [MongooseModule.forRoot('mongodb://localhost/nest')],
and i have it like this

tough bough
candid oar
#

yes so this is to connect to the database right ?

tough bough
#

Yes

candid oar
#

okay

#

i wil read the docs

candid oar
# tough bough Yes

hello i have read through the documentation i have managed to fix everything but i somehow have a problem connecting can you help me there maybe ?

tough bough
#

What's the issue?

candid oar
#

i get Unable to connect to the database. Retrying (9)...
[Nest] 93732 - 07/19/2023, 12:24:32 AM ERROR [ExceptionHandler] Authentication failed.

#

but the username and password is right

candid oar
tough bough
#

If authentication failed, it's not right. How are you running mongo locally?

candid oar
#

no on docker here is the container ```docker
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
c818d9871e95 mongo:latest "docker-entrypoint.s…" 12 hours ago Up 12 hours 0.0.0.0:27017->27017/tcp, :::27017->27017/tcp mongodb-db-1

candid oar
tough bough
#

Running locally through docker, got it.

#

Wat do the container logs say?

candid oar
# tough bough Running locally through docker, got it.

{"t":{"$date":"2023-07-18T22:25:50.362+00:00"},"s":"I",  "c":"ACCESS",   "id":20251,   "ctx":"conn429","msg":"Supported SASL mechanisms requested for unknown user","attr":{"user":{"user":"mongodb","db":"mongodb/"}}}
{"t":{"$date":"2023-07-18T22:25:50.363+00:00"},"s":"I",  "c":"ACCESS",   "id":20249,   "ctx":"conn429","msg":"Authentication failed","attr":{"mechanism":"SCRAM-SHA-256","speculative":true,"principalName":"mongodb","authenticationDatabase":"mongodb/","remote":"172.20.0.1:41404","extraInfo":{},"error":"UserNotFound: Could not find user \"mongodb\" for db \"mongodb/\""}}
{"t":{"$date":"2023-07-18T22:25:50.364+00:00"},"s":"I",  "c":"NETWORK",  "id":22944,   "ctx":"conn428","msg":"Connection ended","attr":{"remote":"172.20.0.1:41394","uuid":"44e0c60d-baa1-4ade-9faf-d97702a2d5ef","connectionId":428,"connectionCount":1}}
{"t":{"$date":"2023-07-18T22:25:50.380+00:00"},"s":"I",  "c":"NETWORK",  "id":22944,   "ctx":"conn429","msg":"Connection ended","attr":{"remote":"172.20.0.1:41404","uuid":"edb093e4-a757-4322-9524-93f7da117c90","connectionId":429,"connectionCount":0}}
{"t":{"$date":"2023-07-18T22:25:53.824+00:00"},"s":"I",  "c":"NETWORK",  "id":22943,   "ctx":"listener","msg":"Connection accepted","attr":{"remote":"172.20.0.1:41416","uuid":"48bb4858-ea54-4a76-8752-2049424cad9e","connectionId":430,"connectionCount":1}}
{"t":{"$date":"2023-07-18T22:25:53.831+00:00"},"s":"I",  "c":"NETWORK",  "id":51800,   "ctx":"conn430","msg":"client metadata","attr":{"remote":"172.20.0.1:41416","client":"conn430","doc":{"application":{"name":"MongoDB Compass"},"driver":{"name":"nodejs","version":"5.6.0"},"platform":"Node.js v18.12.1, LE","os":{"name":"linux","architecture":"x64","version":"6.3.9-arch1-1","type":"Linux"}}}}


tough bough
#

"error":"UserNotFound: Could not find user \"mongodb\" for db \"mongodb/\""
Looks like it's not set up how you think it is

candid oar
tough bough
#

I would first docker compose down && docker compose up -d and check the logs to ensure the user is created as expected

candid oar
#

still getting a authentication failed in the logs

#
"t":{"$date":"2023-07-18T22:54:14.832+00:00"},"s":"I",  "c":"ACCESS",   "id":20251,   "ctx":"conn20","msg":"Supported SASL mechanisms requested for unknown user","attr":{"user":{"user":"mongodb","db":"mongodb"}}}
{"t":{"$date":"2023-07-18T22:54:14.833+00:00"},"s":"I",  "c":"ACCESS",   "id":20249,   "ctx":"conn20","msg":"Authentication failed","attr":{"mechanism":"SCRAM-SHA-256","speculative":true,"principalName":"mongodb","authenticationDatabase":"mongodb","remote":"172.23.0.1:56768","extraInfo":{},"error":"UserNotFound: Could not find user \"mongodb\" for db \"mongodb\""}}
{"t":{"$date":"2023-07-18T22:54:14.834+00:00"},"s":"I",  "c":"ACCESS",   "id":20249,   "ctx":"conn20","msg":"Authentication failed","attr":{"mechanism":"SCRAM-SHA-1","speculative":false,"principalName":"mongodb","authenticationDatabase":"mongodb","remote":"172.23.0.1:56768","extraInfo":{},"error":"UserNotFound: Could not find user \"mongodb\" for db \"mongodb\""}}
{"t":{"$date":"2023-07-18T22:54:14.837+00:00"},"s":"I",  "c":"NETWORK",  "id":22944,   "ctx":"conn19","msg":"Connection ended","attr":{"remote":"172.23.0.1:56752","uuid":"76202859-0a9e-442d-94db-da54e43344b3","connectionId":19,"connectionCount":1}}
{"t":{"$date":"2023-07-18T22:54:14.863+00:00"},"s":"I",  "c":"NETWORK",  "id":22944,   "ctx":"conn20","msg":"Connection ended","attr":{"remote":"172.23.0.1:56768","uuid":"38122efb-acdf-4c6e-9fe3-c5d80ecbc3e3","connectionId":20,"connectionCount":0}}
tough bough
#

I dunno what to say. I generally don't work with mongo. Things look correct from what I can tell, but obviously something isn't working as expected

candid oar
#

oh okay

clever hill
#

That's the problem:
Could not find user \"mongodb\" for db \"mongodb\"

candid oar
#

can you help ?

clever hill
#

You have to set up the connection properly. Usually it's the user missing. Do you actually have a user called "mongodb"?

candid oar
clever hill
#

Can you log in with Compass with the same credentials? @candid oar

candid oar
#

i can do this

clever hill
#

You can do what?

candid oar
#

oh have read wrong i can do that

#

in compass i get auth failed ```js
mongodb://mongodb:mongodb@localhost:27017/mongodb

clever hill
#

So, that user is missing.

#

Can you post your docker compose file?

candid oar
#

yes

#
version: '3.7'
services:
  mongodb_container:
    image: mongo:latest
    environment:
      MONGO_INITDB_ROOT_USERNAME: mongodb
      MONGO_INITDB_ROOT_PASSWORD: mongodb
    ports:
      - 27017:27017
    volumes:
      - mongodb_data_container:/data/db

volumes:
  mongodb_data_container:
candid oar
clever hill
#

See if you can run Compass without any username or password.

candid oar
#

okay

clever hill
#

Just mongodb://localhost:27017

candid oar
clever hill
#

Ok. And how about this URL? mongodb://mongodb:mongodb@localhost:27017

candid oar
clever hill
#

Try to change your username and password to something else other than mongodb. So, docker compose down, change your docker-compose.yaml file and docker-compose up again.

candid oar
#

okay

clever hill
#

Then try to log in with the new credentials you've set.

#

If that doesn't work, try removing the environment user initdb commands and try to access the server without any credentials.

candid oar
#

it dont work this is my docker-compose.yml ```docker
version: '3.7'
services:
mongodb_container:
image: mongo:latest
environment:
MONGO_INITDB_ROOT_USERNAME: rootusername
MONGO_INITDB_ROOT_PASSWORD: rootpass
ports:
- 27017:27017
volumes:
- mongodb_data_container:/data/db

volumes:
mongodb_data_container:
and then i used this urlmongodb://rootusername:rootpass@localhost:27017``` but still getting auth failed

clever hill
#

Try removing the environment user INITDB lines and try to access the server without any credentials.

#

I'm sort of stuck on any further ideas.

#

What is your environment?

candid oar
#

okay so like this ```docker
version: "3.7"
services:
mongodb_container:
image: mongo:latest
ports:
- 27017:27017
volumes:
- mongodb_data_container:/data/db

volumes:
mongodb_data_container:

clever hill
#

Yeah.

candid oar
#

okay

#

and then this database url mongodb://localhost:27017

#

right ?

clever hill
#

yep

#

brb

candid oar
#

i get An error occurred while loading instance info: command hostInfo requires authentication

clever hill
#

On a total whim, down your current container again and try this:

version: '3.7'
services:
  mongodb_container:
    image: mongo:latest
    environment:
      MONGO_INITDB_ROOT_USERNAME: rootusername
      MONGO_INITDB_ROOT_PASSWORD: rootpass
    ports:
      - 27017:27017
    volumes:
      - mongodb_data_container2:/data/db2

volumes:
  mongodb_data_container2:

Then up this new container and login with:
mongodb://rootusername:rootpass@localhost:27017

candid oar
#

okay

#

now i get no error

#

and should i change my app.module connection to this ```js
MongooseModule.forRoot('mongodb://rootusername:rootpass@localhost:27017'),

clever hill
#

That should work now too.

candid oar
#

thx but for one reasony i get js ERROR [ExceptionsHandler] Menu not found Error: Menu not found at MenuService.geMenuByName (/home/barron/MEGA/Projects/restaurant/server/src/menu/menu.service.ts:44:26) at processTicksAndRejections (node:internal/process/task_queues:95:5) at MenuController.getMenuByName (/home/barron/MEGA/Projects/restaurant/server/src/menu/menu.controller.ts:22:12) at /home/barron/MEGA/Projects/restaurant/server/node_modules/.pnpm/@[email protected]_@[email protected]_@[email protected][email protected][email protected]/node_modules/@nestjs/core/router/router-execution-context.js:46:28 at Object.<anonymous> (/home/barron/MEGA/Projects/restaurant/server/node_modules/.pnpm/@[email protected]_@[email protected]_@[email protected][email protected][email protected]/node_modules/@nestjs/core/router/router-proxy.js:9:17)

#

in nestjs

clever hill
#

Ok. Did you have the app running at all before?

candid oar
#

yes but with postgres and prisma

#

now im using mongodb with mongoose

#

i fix the problem but it dont work

clever hill
#

Is your menu service looking for something in the database at startup?

#

Is this an error happening at startup?

candid oar
#

in compass i cant see my schamas

#

no

clever hill
#

Yeah, it's because you have a new volume.

#

What is the database name?

candid oar
clever hill
#

Yeah. You probably need to add that to your connection URL. Also, you can see if you can find the database files where the volume data is stored for docker and copy and paste the data from /db to /db2. Then you'll have your database back.

#

Or do a reseeding of the data, if you have that.

candid oar
#

this is my docker compose ```docker
version: '3.7'
services:
mongodb_container:
image: mongo:latest
environment:
MONGO_INITDB_ROOT_USERNAME: rootusername
MONGO_INITDB_ROOT_PASSWORD: rootpass
ports:
- 27017:27017
volumes:
- mongodb_data_container2:/data/db2

volumes:
mongodb_data_container2:

clever hill
#

The issue was, your database volume was corrupted. So, you can see I added "2" to the volume definition to make a new volume.

candid oar
#

oh okay should i change something in my docker compose ??

clever hill
#

No, the database name is in the database or rather, you need to add it to the URL, for it to be created by the driver.

candid oar
#

so should i change my database url in nestjs

clever hill
#

No, don't change the docker compose. You need to add the database name to your connection URL in your app.

candid oar
#

so like this ```js
MongooseModule.forRoot(
'mongodb://rootusername:rootpass@localhost:27017/restaurant',
),

#

i add the /restaurant

clever hill
#

Then see if you can find the volume data on your computer. Go into the folder and you should see a folder with the old db name.

clever hill
candid oar
#

okay but then i get in my console auth failed

clever hill
#

If you can find the volume data, you can copy and paste the database file (restaurant?) between the two volumes.

candid oar
# clever hill If you can find the volume data, you can copy and paste the database file (resta...
[Nest] 24862  - 07/19/2023, 1:56:45 PM   ERROR [ExceptionHandler] Authentication failed.
MongoServerError: Authentication failed.
    at Connection.onMessage (/home/barron/MEGA/Projects/restaurant/server/node_modules/.pnpm/[email protected]/node_modules/mongodb/src/cmap/connection.ts:413:18)
    at MessageStream.<anonymous> (/home/barron/MEGA/Projects/restaurant/server/node_modules/.pnpm/[email protected]/node_modules/mongodb/src/cmap/connection.ts:243:56)
    at MessageStream.emit (node:events:511:28)
    at MessageStream.emit (node:domain:489:12)
    at processIncomingData (/home/barron/MEGA/Projects/restaurant/server/node_modules/.pnpm/[email protected]/node_modules/mongodb/src/cmap/message_stream.ts:187:12)
    at MessageStream._write (/home/barron/MEGA/Projects/restaurant/server/node_modules/.pnpm/[email protected]/node_modules/mongodb/src/cmap/message_stream.ts:68:5)
    at writeOrBuffer (node:internal/streams/writable:399:12)
    at _write (node:internal/streams/writable:340:10)
    at MessageStream.Writable.write (node:internal/streams/writable:344:10)
    at Socket.ondata (node:internal/streams/readable:774:22)
clever hill
#

🤦🏻‍♂️ Darnit. Ok. That's silly. It should work. The user should be the root admin.

#

Unfortunately, I have to go. Can you work with the database if it at least gives you access to the restaurant database? If yes, I'd say use Compass to create a new user with ownership over the restaurant database and change your app's URL to the credentials of that new user and see if you get it fixed.

#

Other than that, I wish you luck.

candid oar
#

thank you for helping me

clever hill
#

Before I do finally go, try this as your app's connection URL.

mongodb://rootusername:rootpass@localhost:27017/restaurant?authSource=admin

candid oar
#

okay

#

it dont worj just get unable to connect the database

#

and auth failed

clever hill
#

Ok. Sorry I can't help further. Good luck.

candid oar
#

just restarted the server

#

i dont get auth failed