如何构建Node MongoDB项目?

时间:2018-02-16 14:17:41

标签: node.js mongodb

在我的带有mongodb.js的Node.js项目中(注意,不是 mongoose)我有以下结构:

  • index.js
    • 设置数据库连接(db.js)
    • 设置快速服务器(api.js)
  • api.js
    • 启动服务器
    • 定义路由并调用db(db.js)
  • database.js
    • 启动数据库连接,db在文件
    • 中定义为全局
    • 每个db函数使用全局db变量

大致相同:

// 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作为参数传递给所有函数。这种结构的常用方法是什么?

2 个答案:

答案 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 => { })