Search code examples
expressmongoosesubdocument

Find document by ID and push another subdocument


I have two Collection schemas, and I want to insert one Model instance of one schema (FA) inside an array field of the other Model schema (FP):

var FASchema = new Schema({
    Timestamp: Date,
    PrognostizierterBetriebswert: Number,
    posFlexPot: Number,
    negFlexPot: Number,
    Leistungsuntergrenze: Number,
    Leistungsobergrenze: Number,
    posGesEnergie: Number,
    negGesEnergie: Number,
    Preissignal: Number,
    Dummy1: Schema.Types.Mixed,
    Dummy2: Schema.Types.Mixed,
    Dummy3: Schema.Types.Mixed
    //same: Dummy: {}

});
module.exports = mongoose.model("FA", FASchema, 'FA');

and

var FPSchema =  new Schema( {
    _id: String, //mongoose.Schema.Types.ObjectId,
    Demonstrator: Number,
    erstellt: {type: Date, 'default': Date.now},
    von: Date,
    bis: Date,
    Fahrplanabschnitte: { type: Schema.Types.ObjectId, ref: 'FA' },
})    
module.exports = mongoose.model("FP", FPSchema, 'FP');

Now, whenever I create a new FA document, I want to push the FA document into my FP collection inside the array "Fahrplanabschnitte". Either by a reference, or by a schema/nested subdocument... What is the best way to do it and how can I do it?

I call the POST method that should do the job with: router.route('/FA/FPPUT/:FP_id').put(FAController.create_and_push_to_FP_by_ID)

The function itself looks like this: In a first step, a FA instance is created and saved in FA Collection, then the FP collection is updated and into the array "Fahrplanabschnitte", the new FA instance should be inserted. However, it does not work as planned..

exports.create_and_push_to_FP_by_ID=function(req,res) {
    console.log(req.body)
    var fa = new FA(req.body);      

    //SAVE the new instance
    fa.save(function(err) {
        if (err) {
            console.log(err);
            res.status(400);
            res.send(err);
    }
    else {
        console.log("Instanz FA in Datenbank erzeugt!");
        res.status(200);
        res.json({ message: 'FA-Instance created in datbase!' })

    }
    });

    FP.findOneAndUpdate({_id: req.params.FP_id}, function(err, fp) {
        if (err){
            res.send(fa);
        }
        //res.json(fp);
        fp.Fahrplanabschnitte.push(fa._id);
    })      
};

What am I doing wrong?


Solution

  • You are going wrong here

    `fp.Fahrplanabschnitte.push(fa._id); //does't make sense at all` 
    

    above line doesn't do or update anything to the mongodb database...

    you need to use $push operator to update the collection in the database

    exports.create_and_push_to_FP_by_ID=function(req,res) {
        console.log(req.body)
        var fa = new FA(req.body);      
    
        //SAVE the new instance
        fa.save(function(err, fa) {
            if (err) {
                console.log(err);
                res.status(400);
                res.send(err);
        }
        else {
            console.log("Instanz FA in Datenbank erzeugt!");
        FP.findOneAndUpdate({_id: req.params.FP_id}, { $push: { 
          Fahrplanabschnitte: fa._id } } function(err, fp) {
            if (err){
                return res.send(fa);
            }
            res.status(200);
            res.json({ message: 'FA-Instance created in datbase!' })
        })  
        }
        });    
    };