2017-05-19 6 views
0

Ich kann nicht mein Einsatznicht in der Lage Dokument mit ref Mungo speichern

Meine Modelle sparen: Aktion und Type_intervention

var mongoose = require("mongoose"), 
Schema = mongoose.Schema; 

var actionSchema = new Schema({ 
    action: { 
     type: String, 
     required: true, 
     unique: true 
    }, 
}); //Exporter le model 


module.exports = mongoose.model('Action', actionSchema); 

/*-----------------------------------------*/ 

var mongoose = require("mongoose"), 
Schema = mongoose.Schema; 

var type_interventionSchema = new Schema({ 
    type_name_intervention : {type : String}, 
    libelle : {type : String}, 
    Standart : {type : String}, 
    libelle_crt : {type : String}, 
    action : {type: Schema.ObjectId, ref: 'Action'}, 
}); 


//Exporter le model 
module.exports = mongoose.model('Type_intervention',type_interventionSchema); 
/*--------------------------------------*/ 

mein Controller:

var new_type_intervention = new Type_intervention({ 
    type_name_intervention: req.body.type_name_intervention, 
    libelle: req.body.libelle, 
    Standart: req.body.Standart, 
    libelle_crt: req.body.libelle_crt, 
    action: req.body.action, 
    }) 
new_type_intervention.save((err, newinter) => { 
    if (err) { 
     return res.send({ 
      message: 'Error when try to save', 
      'intervention': new_type_intervention, 
      'req.action': req.body.action, 
      'new_type_intervention_action': new_type_intervention.action 
     }); 
    } 
    return res.send({ 
     message: 'Add with succes', 
     'intervention': new_type_intervention 
    }) 
}) 

POSTMAN RUN: Der error ist catched (new_intervention.action nicht apear und dort ist Typ nicht definiert!?) Ich denke, das ist ein Problem

{ "type_name_intervention":"f", 
    "libelle":"f", 
    "Standart":"f", 
    "libelle_crt":"f", 
    "action":"test"} 

    //Results: 
    { 
    "message": "Error when try to save", 
     "intervention": { 
     "type_name_intervention": "f", 
     "libelle": "f", 
     "Standart": "f", 
     "libelle_crt": "f", 
     "_id": "591eb2ccd4325d0e40b2d038" 
    }, 

    "req.body.action": "test", 
    "type of new_type_intervention_action": "undefined" 
    } 

Antwort

0

fand ich die Lösung:

Bevor sparen: Ich versuche, die action_id

Action.findOne({ 
       'action': req.body.action, 
      }) 
      .exec(function (err, found_action) { 
       if (found_action) { 

new_type_intervention.action=found_action._id; // This is GOOD practice 
new_type_intervention.save(); 
        return res.send({ 
         'type': typeof req.body.action, 
         message: 'type intervention ajoutee avec succes ' 
        }) 
       } 

      }) 
zu finden
Verwandte Themen