intro: creating stackexchange clone using node , mongo learn language. working on api.
i have following 'questionschema':
var questionschema = new schema({ _id : {type: string, default: shortid.generate}, title : {type: string, required: true}, question : {type: string, required: true}, user : {type: schema.objectid, ref: 'user'}, points : {type: number, default: 0}, date : {type: date, default: date.now}, answers : [answerschema], votes : [{ user: {type: schema.objectid, ref: 'user', required: true}, vote: {type: number, enum: [-1,0,1]} }], __v : {type: number, select: false} });
the idea when user votes on question points field incremented (or decremented) , userid , vote added votes array. have vote array detect if user has voted , prevent additional votes.
the problem: i'm having trouble checking if user has voted (checking if userid exists in votes array). have been playing around adding method 'hasvoted' questionschema but:
- i'm not sure how make check happen.
- i'm not sure if there way me filter votes array during query (at mongodb) instead of after node gets results.
this attempt @ method know wrong:
//has user voted on question? questionschema.methods.hasvoted = function (userid, cb) { this.votes.filter(function(vote) { if(userid == vote._id) { return '1'; } else { return '0'; } }); };
i recommend make vote schema so
var voteschema = new schema({ user: {type: schema.objectid, ref: 'user', required: true}, vote : {type: number, required: true} }) var questionschema = new schema({ _id : {type: string, default: shortid.generate}, title : {type: string, required: true}, question : {type: string, required: true}, points : {type: number, default: 0}, date : {type: date, default: date.now}, answers : [answerschema], votes : [{type: schema.objectid, ref: 'vote', required: false}] });
then question , go through votes.
questionschema.findbyid(question.id) .populate('votes') .exec(function (err, question) { // go through votes here }
or query if there question user id inside votes
questionschema.find() .and([{_id:questionid,},{votes.user:userid}]) .populate('votes') //dunno if have populate think don't have .exec(function (err, user) { // check if(user) }
or described here findone subdocument in mongoose
//edit or if don't change schema
questionschema.find({votes.user:userid}) .exec(function (err, user) { // should return questions user id in votes want specific question in , in example above }
and if want 1 element array have make projection described here how find document , single subdocument matching given criterias in mongodb collection
Comments
Post a Comment