Reputation: 14831
I try to refactor from javascript object to mongoose object. I have two simple models:
Candidate model:
var candidateSchema = new Schema({
name: String,
score: { type: Number, default: 0, min: -2, max: 2 }
});
candidateSchema.methods.updateScore = function updateScore(newScore) {
this.score = newScore;
};
Vote model containing a list of candidate:
var voteSchema = new Schema({
candidates: [
{ type: Schema.Types.ObjectId, ref: 'Candidate' }
]
});
function candidateAlreadyExists(candidates, newCandidate) {
var alreadyExists = false;
candidates.forEach(function (candidate) {
if (newCandidate.name === candidate.name) {
alreadyExists = true;
}
});
return alreadyExists;
}
voteSchema.methods.addCandidate = function addCandidate(newCandidate, callback) {
var candidates = this.candidates;
if (!candidateAlreadyExists(candidates, newCandidate)) {
candidates.push(newCandidate);
}
this.save(callback);
};
I try to add a static method in my voteSchema to add a new candidate, only if it doesn't exist.
I can't iterate over my candidates (candidates.forEach(function (candidate) {
) because it's an array of _ids and not an array of javascript objects
Someone have an idea ?
Upvotes: 0
Views: 1479