简体   繁体   中英

In mongoose how to iterate over array of ObjectId?

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 ?

It would be better to use $addToSet to let MongoDB do that for you atomically.

voteSchema.methods.addCandidate = function addCandidate(newCandidate, callback) {
    this.candidates.addToSet(newCandidate._id);
    this.save(callback);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM