How to think in MongoDB/Mongoose ?!
-
Hello, all! I'm experienced front-end developer. Few months ago I started play with back-end technologies - nodejs, express, mongo,mongoose. I can get everything quickly. Just need some help to initiate thinking over there. Now I develop polls application and struggle with how to structure my mongoose schemas to implement my features. Also there is implemented simple authentication. Don't worry everything will be explained step by step. Features: - User can create poll on "POST /polls". Poll contains question:string, and options:[string]; - User can vote for poll on "POST /polls/:pollID/vote" as select option index; - User can get polls on "GET /polls?...". But you receive their vote result only if you are creator or voter. And you can see always the count of all voters; - User can bookmark poll on "POST /polls/:pollID/bookmark; - User can get all bookmarked polls on "GET /poll/:pollID/bookmarks sorted by bookmark date; Front-end poll object looks like; -Always show question, options, votesCount; -Only show vote if user is creator or voted for the poll; -Always show if user bookmarked the poll; My current Poll schema:
{
question: {
type: mongoose.Schema.Types.String,
required: true,
},
options: {
type: [{
type: mongoose.Schema.Types.String,
required: true,
}]
},
optionsVote: {
type: mongoose.Schema.Types.Map,
of: mongoose.Schema.Types.Number,
},
createdAt: {
type: mongoose.Schema.Types.Date,
default: Date.now,
},
votes: {
type: [{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
option: mongoose.Schema.Types.Number,
}]
},
votesCount: {
type: mongoose.Schema.Types.Number,
default: 0,
},
creator: {
type: mongoose.Schema.Types.ObjectId,
required: true,
},
bookmarks: {
type: [{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
createdAt: mongoose.Schema.Types.Number,
}]
},
}What I did then ...
// First added useless field in the schema I think. That helped my to limit the access(with query, not with pure js on the server) of $options