Sudheer KB
Sudheer KB

Reputation: 1606

Unable to check whether the value exists inside nested Model in mongoose

I am creating poll app. My schema definitions are as below

var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/pollApp');

var userSchema = new mongoose.Schema({
    username: { type: String, required: true},
    phonenumber: { type: String, required: true, unique: true}
});

var option = new mongoose.Schema({
    title: {type: String, required: true},
    votes: { type: Number, default: 0 },
    voterList: {type: []}
});

var poll = new mongoose.Schema({
    question: { type: String, required: true, unique: true},
    options: { type: [option], required: true},
    showVoters: {type: Boolean, default: false}
});

mongoose.user = mongoose.model('User', userSchema);
mongoose.poll = mongoose.model('Poll', poll);
module.exports = mongoose;

voterList will contain all the voters name.
Before adding vote i want to check whether user has already voted for the poll(need to check user exists in each voterList array).
How to accomplish this?

Upvotes: 0

Views: 34

Answers (1)

Pankaj kumar Panigrahi
Pankaj kumar Panigrahi

Reputation: 761

If you want unique values in the voterList array, you can use $addToSet for pushing a user in the voterList.

but if you want to do some kind of validation. It is better you do a get query which checks if user is already present in the array.

if yes, throw a message saying user already voted else add the user to voterlist

For checking an user is already present in voterList array, it is very simple actually.

You can use a find query like below:

find({voterList:'585ce839c84f5d3d1ef15d56'})

Even if voterList is an array, mongo will see if the provided value is present in the array or not.

Upvotes: 2

Related Questions