Mongoose: find all referenced documents

144 Views Asked by At

I have 2 schemas:

var pollSchema = new mongoose.Schema({
    title: String,      
    created: {
        type: Date, default: Date.now
    },
    options: [{
        label: String,
        count: {
            type: Number,  default: 0
        },
        backgroundColor: {
            type: String,  default: '#fff'
        }
    }],
    author:{
        id:{
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },              
        username: String        
    }
});



var userSchema = new Schema({
    username: {type: String, unique:true},
    email: {type: String, unique:true, lowercase: true},
    password: String
});

Now each poll will store data of it's author. Questions:

  • How can I redesign my schemas - so I will be able to find all the polls belong to particular user?
  • Or should I leave the schemas the same and find another approach?
1

There are 1 best solutions below

0
On

you can still find all the polls belonging to a particular user . You have the author.id for that.

Also you can keep an array as var userSchema = new Schema({ username: {type: String, unique:true}, email: {type: String, unique:true, lowercase: true}, password: String, polls: [] });

And every time a user polls, push the userId inside the polls array, which you can later populate or get the count.