[英]In mongoose how to iterate over array of ObjectId?
我嘗試從javascript對象重構為貓鼬對象。 我有兩個簡單的模型:
候選模型:
var candidateSchema = new Schema({
name: String,
score: { type: Number, default: 0, min: -2, max: 2 }
});
candidateSchema.methods.updateScore = function updateScore(newScore) {
this.score = newScore;
};
包含候選人列表的投票模型 :
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);
};
我嘗試在我的表決模式中添加靜態方法以添加新的候選者,只要它不存在。
我無法遍歷我的候選對象( candidates.forEach(function (candidate) {
),因為它是_ids數組而不是javascript對象的數組
有人有主意嗎?
最好使用$addToSet
來讓MongoDB自動執行此操作。
voteSchema.methods.addCandidate = function addCandidate(newCandidate, callback) {
this.candidates.addToSet(newCandidate._id);
this.save(callback);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.