我正在使用 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 尚未返回具有 then
和 catch
的内容,您可以创建一个 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/