2

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?

MMMM
  • 3,320
  • 8
  • 43
  • 80
  • Eliminate the `module.exports = mongoose.model("FA", FASchema, 'FA')` and declare it as the `FBSchema` sub-document right above the `FPSchema`. The data type (schema path) for Fahrplanabschnitte should be an Array with a reference to `FASchema`, like so: `Fahrplanabschnitte: [FASchema];` Try this and let me know – rags2riches-prog May 16 '18 at 14:03
  • You are also saving the instance when you instead need to reference the document to be able to create the sub-document. When updating or creating a new sub-document in Mongoose the flow is 1. Identify Document 2. Create sub-document 3. Save the Document and 4. Send the Response. – rags2riches-prog May 16 '18 at 14:12
  • @rags2riches, I did something similar, but didnt remove the exports, because I need FA on some other js file where the CRUD logic resides.. so instead I did: var mongoose = require("mongoose"); var Schema = mongoose.Schema; var FA = require("./FA"); var FASchema = require('mongoose').model('FA').schema; var FPSchema = new Schema( { _id: String, //mongoose.Schema.Types.ObjectId, Demonstrator: Number, erstellt: {type: Date, 'default': Date.now}, von: Date, bis: Date, Fahrplanabschnitte: [FASchema] }) – MMMM May 16 '18 at 14:55
  • You have to declare the sub-document above the document and use the module instance in whatever file you want for your logic. Rather than creating 2 exports for the same Schema (it won't work) just export the module object where you need it. Then you have to use the flow as explained above to make CRUD operations with the sub-document. 1. Identify the document 2. CRUD operations with sub-document 3. Save document and 4. Send a response. That's it. Let me know how you get on the exact error you get if any – rags2riches-prog May 16 '18 at 16:51

1 Answers1

1

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!' })
    })  
    }
    });    
};
Ashh
  • 44,693
  • 14
  • 105
  • 132
  • ok thanks I did it with [schema] once and with [_id] field, both seemed to work now..: $ push was the solution, for [schema] I push the whole FA document, for the [.id] I push only the .id field of my Model... I am just working on the problem now, how to recover the entries from the .id field and populate my collection with those documents, referenced by the ID in some other collection... somehow it will not work with .populate method: FP.find().populate({path:"Fahrplanabschnitte"}).exec(function(err,fp) , and also with just .populate("field.."),but maybe thats a question for another thread... – MMMM May 17 '18 at 11:58
  • great it works for you... And yes If you have another question then please ask a new one... – Ashh May 17 '18 at 12:02