0

I am trying to do a check to see if a logged-in user's id req.user.id. is in an array of followers of the user being checked in req.params.id, bit for some reason it doesn't work.

router.get('/api/:id/isfollowing', auth, async (req, res) => {

    if (req.params.id==req.user._id) {
        return res.status(200).send({ "isfollowing": "Myself" })
    }

    try {
        const followers = await Follow.find({
            user: req.params.id
        })

        let followersArr = followers.map(follower=>{
            return follower.followedBy
        })

        const yes = followersArr.includes(req.user._id)
        // const yes = followersArr.filter((objId) => objId==req.user._id)

        console.log(yes, followersArr, req.user._id)

        if (yes===false) {
            return res.status(200).send({ "isfollowing": false })
        }

        return res.status(200).send({ "isfollowing": true })

    } catch (e) {
        res.status(500).send()
    }
})

for some reason the check doesn't work and even when using the filter, it still returns nothing. But when I console.log the values, it is right there.

[] [ 5fa4f0af4a7bf5471c41e225, 5f9dc1777a695570e878424d ] 5f9dc1777a695570e878424d

EDIT schemas below

User schema

const userSchema = new mongoose.Schema({
    fullname: {
        type: String, 
        required: true,
        trim: true,
        lowercase: true
    },
    username: {
        type: String,
        unique: true,
        required: true,
        trim: true,
        lowercase: true
    },
    email: {
        type: String,
        unique: true,
        required: true,
        trim: true,
        lowercase: true,
        validate(value) {
            if (!validator.isEmail(value)) {
                throw new Error('Email is invalid')
            }
        }
    },
    password: {
        type: String,
        required: true,
        minlength: 7,
        trim: true,
        validate(value) {
            if (value.toLowerCase().includes('password')) {
                throw new Error('Passwoed cannot contain "password"')
            }
        }
    }
})

follow schema

const followSchema = new mongoose.Schema({
    // the logged in user who will be trying to follow someone will be added to "followedBy"
    // the user who is getting followed will be added to "user"
    user: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    },
    followedBy: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'Showcase'
    }
}, {
    timestamps: true
})

I gave follow its own schema so I can record other info like time and other info whenever a user follows another.

2
  • Can you provide your schema and an examplo for your collection? Thanks Commented Nov 9, 2020 at 18:51
  • @J.F. I just updated the post and added my model schema Commented Nov 9, 2020 at 18:57

2 Answers 2

1

If I've understand well you only need a simple query.

Since you only want to know if the id is into an array, you can check that directly with mongo. You don't need load every document into memory and use JS functions like filter or something similar.

You only need a query similar to this:

db.collection.find({
  "user": ObjectId("user_id"),
  "followedBy": ObjectId("follower_id")
})

This will return a document that match both values.

Check here it works and tell me if is the behaviour and output you expect.

Also I will code a mongoose query and I'll update the answer.

You can use also this query in mongoose to get how many documents find the query:

var find = await model.find({"user":mongoose.Types.ObjectId(user_id),"followedBy":mongoose.Types.ObjectId(follower_id)}).countDocuments()
Sign up to request clarification or add additional context in comments.

1 Comment

You are welcome! I have added some mongoose code in case it cuold help.
1

Includes cannot be used in this case since you are trying to find ObjectId in an array.

To find if req.user._id is present in followersArr, use Array.some() function as below

const yes = followersArr.some(followerId=>{followerId.equals(req.user._id)})

The some call will iterate over the followersArr array, calling equals on each one to see if it matches req.user._id and stop as soon as it finds a match. If it finds a match it returns true, otherwise false.

You can't use something simpler like indexOf because you want to compare the ObjectIDs by value, not by reference.

1 Comment

bro, it still doesn't work for some reason even when I console.log the values and it's supposed to return true

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.