【问题标题】:Is it possible to create a custom mongoose querying function?是否可以创建自定义猫鼬查询功能?
【发布时间】:2017-12-30 11:25:17
【问题描述】:

我正在使用 Node.js 和 ExpressJS 编写服务器代码。我的数据库是 MongoDB,我使用 MongooseJS 作为中间件。

服务器有许多端点,几乎每个端点在开始时都有相同的代码 - 查询数据库以检索已分配到所选房间的设备。简化的重复代码如下:

Room
        .findOne({ _id: roomId })
        .populate({
            path: "deviceGroups",
            populate: {
                path: "devices"
            }
        })
        .exec(() => {
            Device.findOne({ _id: deviceId }).exec((err, device) => {
                if (err) {
                    res.send(err);
                } else {
                    // do anything you need with the results here
                }
            });
        });

我知道查询是异步的,所以如果我想对查询的结果做任何事情,我必须在查询的回调函数中做。另外,在将查询提取到外部函数时,我想没有办法传递 express'res 对象,对吧?在查询期间需要处理潜在的错误。

我的问题是:考虑到上述关于异步的信息,是否可以创建一些像下面这样的自定义函数来检索设备?函数的调用结果可以分配给某个变量。我想如果有可能的话,它应该用一些 JS 的 promise 处理程序来包装,对吧?

我想要实现的是减少重复代码的数量。

原型功能:

const getDevice = (roomId, deviceId) => {
    Room
        .findOne({ _id: roomId })
        .populate({
            path: "deviceGroups",
            populate: {
                path: "devices"
            }
        })
        .exec(() => {
            Device.findOne({ _id: deviceId }).exec((err, device) => {
                return device;
            });
        });
};

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    如果 Room.exec 尚未返回具有 then 和 catch 的内容,您可以创建一个承诺

    function getDivice(roomId){
      return new Promise(
        (resolve,reject)=>
          Room
          .findOne({ _id: roomId })
          .populate({
              path: "deviceGroups",
              populate: {
                  path: "devices"
              }
          })
          .exec(() => {
              Device.findOne({ _id: deviceId }).exec((err, device) => {
                  if (err) {
                      reject(err);
                  } else {
                    resolve(device);
                      // do anything you need with the results here
                  }
              });
          })
      );
    }
    
    //call it like this:
    getDivice(someid)
    .then(
      divice=>{
        //do something with divice
      }
    )
    .catch(
      err=>{
        //do something with the error
      }
    )
    

    【讨论】:

      猜你喜欢
      • 2018-08-03
      • 2019-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-27
      相关资源
      最近更新 更多