如何在mongoose中查找数据并将数据推送到数组中

时间:2017-04-10 18:03:17

标签: node.js mongoose

我使用过这种模式: -

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 []数组中。

1 个答案:

答案 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}});