1

So I have something like Survey Schema (I am using mongoose).

In this Schema, for each voting option, I have votes[] array that contains ObjectIds of Users.

Now I want to check if User can vote again, or if he already voted?

The simple solution is iterating thru votes with .indexOf() and checking if id exists. Now this is a blocking way for Node JS, since this operation is sync.

Is there a way to do this with Mongo aggregate or query? So for each voting option I would get additional field like:

didIVoted: true

My Schema looks like this:

const SurveySchema = new Schema({
    title: {
        type: String
    },
    options: [{
        value: String,
        votes: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }]
    }]
}, { timestamps: true })

1 Answer 1

1

You can use $addFields and $map to overwrite existing options field. To check if userId exists in votes array you can use $indexOfArray

SurveySchema.aggregate([
    {
        $addFields: {
            options: {
                $map: {
                    input: "$options",
                    in: {
                        value: "$$this.value",
                        votes: "$$this.votes",
                        didIVote: { $ne: [ { $indexOfArray: [ "$$this.votes", userId ] }, -1 ] }
                    }
                }
            }
        }
    }
])
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.