简体   繁体   English

使用 mongoose 的 node.js 存储库模式

[英]Repository Pattern for node.js using mongoose

I am a newbie to node.js, coming from a .net background.我是 node.js 的新手,来自 .net 背景。 I would like to use some of the design patterns I used with c#.net.我想使用我在 c#.net 中使用的一些设计模式。 I am running into a few complications however, due to the differences in object oriented nature between c# and JavaScript.但是,由于 c# 和 JavaScript 之间面向对象性质的差异,我遇到了一些复杂情况。

In particular, I would like to implement the repository pattern but have not been able to find a lot of examples doing this with node.特别是,我想实现存储库模式,但无法找到很多使用 node.js 执行此操作的示例。 The way JavaScript and mongoose are set up are making it a little hard to wrap my mind around this one. JavaScript 和 mongoose 的设置方式让我有点难以理解这一点。

I was referred to the following url for an example https://github.com/iainjmitchell/mongorepositiory , I could be wrong, but I do not see where this example allows for you to pass callbacks that would allow your code to handle any errors that may arise after the db call is made as opposed to how it is ordinarily done using mongoose.我参考了以下 url 的示例https://github.com/iainjmitchell/mongorepositiory ,我可能是错的,但我看不到此示例允许您传递回调的位置,以允许您的代码处理任何错误这可能在进行 db 调用后出现,而不是通常使用 mongoose 完成。

I will explain two functionality of CRUD operation ie Create and Read and you will have the idea for rest.我将解释 CRUD 操作的两个功能,即创建和读取,您将有了休息的想法。 We will have the following layer:我们将有以下层:

  • controller控制器
  • service服务
  • repository存储库

Let first set up our model using mongoose schema.让我们首先使用猫鼬模式设置我们的模型。 This is inside the test.model.js.这是在 test.model.js 中。

var mongoose = require("mongoose");
var Schema = mongoose.Schema;

var userSchema = new mongoose.Schema({
  username: String,
  password: String, //hash created from password
  created_at: { type: Date, default: Date.now }
});

module.exports = mongoose.model("User", userSchema);

I will not explain how the controller will request a service layer for posting or receiving the data.我不会解释控制器将如何请求服务层来发布或接收数据。 It is just about calling a method from the service layer.它只是从服务层调用一个方法。 So inside service layer, for sake of example say test.service.js.所以在服务层内部,例如说 test.service.js。 we will request repository layer like below.我们将请求像下面这样的存储库层。 Provide the path for the repository and for your model as your folder structure.提供存储库和模型的路径作为文件夹结构。

const repository = require("../../models/repository");
var mongoose = require("mongoose");
var User = mongoose.model("User");

function createTestData(user1) {
  return new Promise(function(resolve, reject) {
    let user = new User(user1);// user1 is a object to be saved
    repository
      .create(user)
      .then(data => {
        resolve({
          data: data
        });
      })
      .catch(err => {
        reject(err);
      });
  });
}

function listTestData() {
  let params = {
    limit: 10
  };
  return new Promise(function(resolve, reject) {
    repository
      .list(User, params)
      .then(data => resolve(data))
      .catch(err => reject(err));
  });
}

Now we will create a repository so that every other service can call this repository for CRUD functionality.现在我们将创建一个存储库,以便其他所有服务都可以调用此存储库以实现 CRUD 功能。 This will help to reduce boilerplate code.这将有助于减少样板代码。

function create(Model) {
  return new Promise((resolve, reject) => {
    Model.save(function(err, user) {
      if (err) {
        reject(err);
      }
      resolve(user);
    });
  });
}

function list(Model, queryParams) {
  return new Promise((resolve, reject) => {
    Model.find({})
      .limit(parseInt(queryParams.limit))
      .exec(function(err, data) {
        if (err) reject(err);
        resolve(data);
      });
  });
}

That's all.就这样。 I have tried to explain as simple as possible.我试图解释得尽可能简单。 You may need to configure other settings like to connect to the database.您可能需要配置其他设置,例如连接到数据库。 But if you can make this work you can add other functionality to the repository.但是,如果您可以完成这项工作,则可以向存储库添加其他功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM