Skip to content
Advertisement

Please help, I have a problem, My conditional didnt work with data I gained from mongoDB.find()

I have a problem, I code using javascript and I use mongodb or mongoose as the database. I have a little information about async / await

I made a variable called “thread” to get data from mongoDB using const thread = await Threads.findOne({threadId})

the thread will have data: { “_id”: “6044d0d8940c3b2494ce135d”, “threadId”:”A001}

After that I want to use the _id from this “thread” to check the users markedPost, if there is the same threadId from user markedPost with _id from thread, I want to remove it by using splice

the users markedPost will have data for example: {“threadId”: “6044d0d8940c3b2494ce135d”, “threadId”: “6044d0e0940c3b2494ce135e”}

But the problem is the conditional code “if(markpost[i].threadId === thread._id)”, it didnt work, it didnt do anything even when the markpost[i].threadId is the same with thread._id, it didnt do the console.log(“found ya”)

So can u help me how to solve this? Here is my code below, and I also commented on the part that didnt work

    const thread = await Threads.findOne({threadId})

    const users = await Users.find({"markedPost.threadId":{
        $in:[thread._id]
    }})

    if(users.length > 0){
        await users.map(async user=>{
            const markpost = user.markedPost;
            let index = 0;

            for (let i = 0; i < markpost.length; i++) {
                console.log(markpost[i].threadId)
                console.log(thread._id)
                if(markpost[i].threadId === thread._id){
                    //this if didnt work at all, I dont know why, even when the threadId is the same with thread._id
                    console.log("found ya")
                    index = i;
                    break
                }
                console.log(markpost[i])
            }

            markpost.splice(index,1);

            await Users.findOneAndUpdate({
                userId:user.userId
            },{
                markedPost:[...markpost]
            })  
            
        })
    }

This code will just print the threadId from the user markedPost, and will not do the console.log(“found ya”), even when the thread._id is the same with the markedPost.threadId The result is like below:

markpost[i].threadId: 6044d0e0940c3b2494ce135e
thread._id : 6044d0e0940c3b2494ce135e
{
  threadId: '6044d0e0940c3b2494ce135e',
  date: 2021-03-07T13:15:45.713Z
}
markpost[i].threadId: 6044d0d8940c3b2494ce135d
thread._id : 6044d0e0940c3b2494ce135e
{
  threadId: '6044d0d8940c3b2494ce135d',
  date: 2021-03-07T13:15:47.967Z
}

Advertisement

Answer

Edit : My mistake in here, the thread._id type is ObjectId, while the other one is string, thus it wil return false

Thanks to Vishnu for correcting my mistake

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement