在我的带有mongodb.js的Node.js项目中(注意,不是 mongoose)我有以下结构:
大致相同:
// database.js
let db;
module.exports = {
connect() {
db = set value here;
},
findUser() {
db.find(query);
}
};
现在我想将每个db函数重构为它自己的文件夹,如database / user.js,但我不确定如何使用单独的文件处理全局db var?
// database/users.js
module.exports = {
findUser() {
db.find(query); <-- how to pass the db connection
}
};
我想避免将db作为参数传递给所有函数。这种结构的常用方法是什么?
答案 0 :(得分:1)
// database.js
let db;
module.exports = {
connect() {
db = set value here;
},
findUser() {
db.find(query);
},
getDb(){
return db;
}
};
和
// database/users.js
var db = require('database.js).getDb();
module.exports = {
findUser() {
db.find(query); <-- how to pass the db connection
}
};
答案 1 :(得分:0)
for creating a project using mongodb with nodejs you need to learn the code structure as described below..it should contains modules,controller,services etc.inside the controller you need to write the functions through which you can call certain services to perform an action.
i will tell you in detailed how to start with controller and services
CONTROLLER INCLUDES
import { Controller, Post, Body, Param } from '@nestjs/common';
import { DepartmentService } from './department.service';
import { ApiTags } from '@nestjs/swagger';
import { DepartmenDto } from './dto/addDepartment.dto';
@Controller('department')
@ApiTags('department')
export class DepartmentController {
constructor(private service: epartmentService) { }
@Post('addDepartment')
async addDepartment(
@Body()registerDepartmentDto: addDepartmentDto) {
return await this.service.insertDepartment(registerKidsDto).then(res => {
return res;
});
}
}
import { Injectable, Inject } from '@nestjs/common';
import { Department} from './interface/department.interface';
import { Model } from 'mongoose';
import { DepartmenDto } from './dto/addDepartment.dto';
@Injectable()
export class DepartmentService {
constructor(
@Inject('DEPARTMENT_MODEL') private readonly DepartmentModel: Model <Kids>,
) {}
async addDepartment(Departmentdto: DepartmentDto) {
const createdCat = new this.DepartmentModel(Departmentdto);
return await createdCat.save();
}
}
I HAVE CREATED A DEPARTMENT MODULE AND WROTE SERVICE FOR ACCESSIUNG THIS.
类似的其他粗体操作,您可以将其用作参考。如果要在控制器中传递参数,可以像调用它一样 @Post('getDeaprtmentDetails /:departmentId') 异步getDepartmentDetails( @Param('departmentId')departmentId:字符串){ 返回等待this.service.retrieveDepartmentInfo(departmentId).then(res => { })