Home > OS >  finding multiple documents with mongoose
finding multiple documents with mongoose

Time:04-19

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)
        }
    }
}

I'm running this code when I console.log(postId) it returns all the posts with that id, but when I try to retrieve all documents with that id it returns just one document

CodePudding user response:

findById will only return one record or null, an ID is the _id field on each document in a collection, which is a unique value

find is the equivalent of a where command in SQL, it returns as many documents that match the query, or an empty array

passing $in as a query to find looks for an array of matching document for the user id's

so if you already know the document _id's, then find will return the ID's so long you have passed an array of valid 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")

  • Related