0

Im trying to create a mongoose query using the $in operator which specifically requires an array as the input.

I pass in an array of search.interests, however depending on the user input the interests array could be either 1 value or many. If it is many it works fine, if its a single value then the $in operator fails.

"$in needs an array"

As i don't know how many interests my user will choose, how do i ensure search.interests is an array even with one value, so i can carry on using $in operator for both use cases.

search(req, res) {

    let search = req.query;

    console.log(search.interests);

    User.where('profile.interests').in(search.interests)
        .select('_id')
        .exec((err, users) => {

            if (err) {
                return res.json(err);
            }

            return res.json(users);

        });

}

1 Answer 1

1

Force to array type : http://rextester.com/JFXO55055

interests_array = [].concat(search.interests || [])

in your code :

User.where('profile.interests').in([].concat(search.interests || []))
    .select('_id')
    .exec((err, users) => {

        if (err) {
            return res.json(err);
        }

        return res.json(users);

    });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.