繁体   English   中英

为什么这个数组被认为是object,如何处理?

[英]Why is this array considered to be an object, and how to handle it?

大家,早安。 我有一个小问题。 我想检查数据库中的一个字段,并将其存储到一个变量中:为此,我这样做了:

async function buildUsername(value) {
    const { db } = await connectToDatabase(URI, DATABASE);
    let obj = await db.collection(COLLECTION).find({username: value}).toArray()
    //here I want to do something like: let username = obj.username
    return typeof obj
}

这返回给我object

如果我记录obj它会输出如下结构:

[
    {
        name: "tom"
        username: "tomhopkins"
        //etc...

    }
]

我想访问用户名并将其存储到变量中。 如果我这样做: username = obj[0].username它不起作用,因为它说obj不是一个数组,它是一个 object。

我不得不说我不能用回调来做到这一点,因为我需要返回一个尚未存储在数据库中的用户名。

例如:如果存储了一个用户名为“tomhanks”的文档,并且有另一个同名的人,我无法注册相同的用户名。 I call the function username, add a suffix (an integer at the end) and check again if there is another one.if there is not then I return it, otherwise i call the function recursively with the username + suffix and so on.

有什么建议么?

非常感谢!

.find() 方法返回一个数组,尝试使用.findOne():它返回一个 object:

let obj = await db.collection(COLLECTION).findOne({username: value})
// here you can use obj.username

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM