gpt4 book ai didi

node.js - Mongodb native 驱动程序 toArray() on limit(1)?

转载 作者:行者123 更新时间:2023-12-03 01:59:18 25 4
gpt4 key购买 nike

根据文档,通过 Promise 检索一个文档的官方方法是 .find().limit(1).toArray() 根据此处的示例:https://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#find

我觉得很烦人的是,他们在将 Promise 返回到数组时强制得到一个结果。与以下返回单个文档的方法 find().limit(1).next(function(err, doc){}) 不同。 无论如何,还是只是为了适应?

此外,findOne 在这里已贬值 https://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#findOne并指出应使用以下内容:find().limit(1).next(function(err, doc){})。然而这里https://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#find它在示例中声明使用 then()

那么,我应该使用 next() 还是 then()

最佳答案

如果你想返回单个对象,可以使用 find().limit(1).toArray().then(arrs =>{return arrs[0] || null }); ;

collection.find()查询所有匹配文档返回一个数组对象;

关于node.js - Mongodb native 驱动程序 toArray() on limit(1)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35205779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com