'how to use estimatedDocumentCount of mongoose in nestJs?
I have a problem, I'm trying to refactor my nodeJs server with nestJs.
The idea here is to check when starting the server if the 'Roles' collection already exists and contains entries, if not, we generate the roles in the mongoDB collection.
I have this folder stucture : mongoose schemas in a 'models' folder and an index.js that imports them:
./models/role.model.js
const mongoose = require("mongoose");
const Role = mongoose.model(
"Role",
new mongoose.Schema({
name: String
})
);
module.exports = Role;
./models/index.js
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const db = {};
db.mongoose = mongoose;
db.user = require("./user.model");
db.role = require("./role.model");
db.ROLES = ["user", "admin", "moderator"];
module.exports = db;
and then, in server.js, i import index.js as db then i define Role as db.role and i use an init function with 'Role.estimatedDocumentCount' to count the number of documents and do some logic:
./server.js
const db = require("./models");
const Role = db.role;
[...]
function init() {
Role.estimatedDocumentCount((err, count) => {
if (!err && count === 0) {
new Role({
name: "user"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'user' to roles collection");
});
}
});
}
It's working super fine on my nodeJs server, but problems comes with the new nestJs server, basically, i think it's a type issue, and i'm not sure if my method is legit in a nestjs environement, assuming i'm an absolute begginer in it... This is what i tried:
./schemas/role.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
export type RoleDocument = Role & Document;
@Schema()
export class Role {
@Prop()
name: string;
}
export const RoleSchema = SchemaFactory.createForClass(Role);
./schemas/index.ts
import mongoose from 'mongoose';
import { User } from './user.schema'
import { Role } from './role.schema'
mongoose.Promise = global.Promise;
export const db = {
mongoose: mongoose,
user: User,
role: Role,
ROLES: ["user", "admin", "moderator"]
};
./main.ts
[...]
import { db } from './auth/schemas';
const Role = db.role;
[...]
function init() {
Role.estimatedDocumentCount((err, count) => {
if (!err && count === 0) {
new Role({
name: "user"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'user' to roles collection");
});
}
});
}
But it's not working, i get this error:
And when i check the type on the nodeJs server i have this:
But on nestJs server i get another type, this is why i think my issue comes from type, or maybe that method can't work the same way than on nodeJs for some reason...
EDIT: i also tried getting directly the roleSchema in my main.ts file, i'm getting a more interesting type, but it's not working either:
import { RoleSchema } from './auth/schemas/role.schema';
function init() {
RoleSchema.estimatedDocumentCount((err, count) => {
if (!err && count === 0) {
new Role({
name: "user"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'user' to roles collection");
});
}
});
}
EDIT2: reply to gianfranco
auth.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt';
import { MongooseModule } from '@nestjs/mongoose';
import { PassportModule } from '@nestjs/passport';
import { JwtStrategy } from './strategies/jwt.strategy';
import { LocalStrategy } from './strategies/local.strategy';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { UserSchema } from './schemas/user.schema';
import { RoleSchema } from './schemas/role.schema';
@Module({
imports: [
ConfigModule.forRoot(),
MongooseModule.forFeature([{ name: 'User', schema: UserSchema },{ name: 'Role', schema: RoleSchema}]),
PassportModule,
JwtModule.register({
secret: process.env.JWT_SECRET,
signOptions: { expiresIn: '60s' },
}),
],
providers: [AuthService, LocalStrategy, JwtStrategy],
controllers: [AuthController],
exports: [AuthService],
})
export class AuthModule {}
auth.controller.ts
import {
Body,
Controller,
Post,
Get,
Res,
Request,
UseGuards,
ValidationPipe,
} from '@nestjs/common';
import express, { Response } from 'express';
import { AuthService } from './auth.service';
import { AuthCredentialsDto } from './dto/auth-credentials.dto';
import { LocalAuthGuard } from './guards/auth.guard';
import { JwtAuthGuard } from './guards/jwt-auth.guard';
@Controller('auth')
export class AuthController {
constructor(private authService: AuthService) {}
@Post('signup')
async signUp(
@Body(ValidationPipe) authCredentialsDto: AuthCredentialsDto,
): Promise<void> {
return await this.authService.signUp(authCredentialsDto);
}
@UseGuards(LocalAuthGuard)
@Post('signin')
async signIn(@Request() req) {
return this.authService.signIn(req.user);
}
@UseGuards(JwtAuthGuard)
@Get('me')
getMe(@Request() req) {
return req.user;
}
}
Thank you very much for your help!
Solution 1:[1]
The key was to implement the logic in auth.service.ts instead of setting it in main.ts.Thanks for your help!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | sikarak |





