'MongoDB/GraphQL: Model.find() to get posts that userId is in likes

in my resolvers I have a method to find user likes with

async function userBookmarks(args, context) {
const user = checkAuth(context);
const posts = await Post.find({likes: {userId: user.id}})
return posts; }

But GraphQL returns an empty array.

For reference, the Post model is

likes: [
{
  userId: String,
  createdAt: String
}],


Solution 1:[1]

I came across a similar problem and fixed it by defining the MongoDB Collection name in the bottom of my MongoDB Schema.

const UserSchema = new mongoose.Schema({
    firstName: {
        type: String,
        required: true
    },
    lastName: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    location: {
        type: String,
        required: false
    }
}, { collection : 'Users' });

EDIT: Use $elemMatch to query several fields.

const posts = await User.find({likes: {$elemMatch: {userId: user.id}}})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1