javascript - 是否可以创建自定义 Mongoose 查询功能?

标签 javascript node.js mongodb express mongoose

我正在使用 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 处理程序包装,对吧?

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

原型(prototype)函数:

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

最佳答案

如果 Room.exec 尚未返回具有 thencatch 的内容,您可以创建一个 promise

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
  }
)

关于javascript - 是否可以创建自定义 Mongoose 查询功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48033466/

相关文章:

javascript - React useEffect 清理函数意外调用

php - 字符串替换和数组的替代方法

node.js - Node.js 数据集中的最近邻居

node.js - 如何使用 mongodb nodejs 驱动程序从文本搜索中仅返回选定的字段

javascript - 如何使用 Meteor 按 ID 从另一个集合中的文档返回文档属性?

javascript - 已弃用的 domLoading 已删除!用什么代替?

javascript - 根据confirm()结果创建一个新对象

node.js - PhanomJS 卡住 [DEBUG] 网页 - updateLoadingProgress : 90

node.js - npm install - 保留node_modules中的现有文件

node.js - Nodejs Express 使用表单中的数据查询 mongolab 以获取单个条目