Mongoose 的 .find
方法即使找到一个结果也会返回 Array,这是符合逻辑的
但例如我确定结果是 1 项或空数组
我如何解构结果或请求 Mongoose 这样做?
Payments
.find({ ... })
.sort({ ... })
.limit(1)
.then(result => {
result = result[0]; // need to write more conditions, this may throw an exception when array is empty
})
最佳答案
此案例并非 Mongoose 特有。
它可以是:
.then(results => {
if (results.length) {
const [result] = results;
...
}
});
或者:
.then(([result]) => {
if (result) {
...
}
});
这两种方式在 Mongoose 中都有效,因为如果结果存在,则预期结果是真实的。
关于javascript - 解构第一个数组项或如何强制 Mongoose 返回对象而不是单项数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49968019/