我使用过这种模式: -
var candidateSchema = new mongoose.Schema({
name : String,
partyName: {type: String, unique: true},
information: String
});
var candidate = mongoose.model("candidate", candidateSchema);
var adminSchema = new mongoose.Schema({
electionName : {type: String, unique: true},
endDate : {type: Date},
candidates : [{type: mongoose.Schema.Types.ObjectId,
ref: "candidate"}]
});
var addElection = mongoose.model("addElection", adminSchema);
如何将candidateSchema的数据推送到candidate []数组中。
答案 0 :(得分:1)
要添加,请使用$push
var candidateItem = new candidate({
name: 'something'
});
candidateItem.save(function(err) {
// addElection schema
addElection.update({id: 123}, {$push: {candidates: candidateItem}}, function(err) {
// saved
});
// addElection schema instance
addElectionItem.update({$push: {candidates: candidateItem}}, function(err) {
// saved
});
});
要删除,请使用$pull
var candidateId = 567;
addElection.update({id: 123}, {$pull: {candidates: candidateId}});