使用猫鼬查找多个文档

finding multiple documents with mongoose

this is what happens when I console.log()

this is what happens when I return all documents with that id, I just get the first document

const followingUsers = await User.find({ _id: { $in: foundUser.followings } })

const getFeedData = async() => {

    for (let user of followingUsers) {


        for (let postId of user.posts) {

            console.log(postId)
        }
    }
}

我是 运行 这段代码,当我 console.log(postId) 它 returns 所有具有该 ID 的帖子时,但是当我尝试检索所有具有该 ID 的文档 returns 只有一个文档

findById只会return一条记录或者null,一个ID就是集合中每个文档上的_id字段,是唯一值

find 等同于 SQL 中的 where 命令,它 return 与查询匹配的文档数,或者一个空数组

$in 作为查询传递给 find 查找用户 ID 的匹配文档数组

因此,如果您已经知道文档的 _id,那么 find 将 return 的 ID,只要您传递了一个有效的 ObjectId

数组
// (pretending these are real id's)
const arrayOfUserIds = [
  ObjectId("5af619de653438ba9c91b291"),
  ObjectId("5af619de653438ba9c91b293"),
  ObjectId("5af619de653438ba9c91b297")
]

const users = await User.find({ _id: { $in: arrayOfUserIds } })

console.log(users.length)

users.forEach((user, index) => {
 console.log(`${index} - `, user._id)
})

// => 3
// => 0 - ObjectId("5af619de653438ba9c91b291")
// => 1 - ObjectId("5af619de653438ba9c91b293")
// => 2 - ObjectId("5af619de653438ba9c91b297")