Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose - create reference on model save

In mongoose, is it possible to create a referenced document while saving the document it is being referenced in? I have tried the below but it does not seem to work for me.

var Model1Schema = new Schema({ 
  foo: String,
  child: { ref: 'Model2', type: ObjectId }
});

var Model2Schema = new Schema({ 
  foo: String
});

mongoose.model('Model1', Model1Schema);
mongoose.model('Model2', Model2Schema);

var m = new (mongoose.model('Model1'));

m.set({
  foo: 'abc',
  child: {
    bar: 'cba'
  }
}).save();
like image 299
mike Avatar asked Feb 07 '13 18:02

mike


1 Answers

Mongoose validation won't allow child to be created since it is a reference, so the second-best thing you can do is creating your own function to create an instance with the corrected child, that has already been saved. Something similar to this, I imagine..

var Model1Schema = new mongoose.Schema({ 
    foo: String,
    child: { ref: 'Model2', type: mongoose.Schema.ObjectId }
});

var Model2Schema = new mongoose.Schema({ 
    foo: String
});

var Model1 = mongoose.model('Model1', Model1Schema);
var Model2 = mongoose.model('Model2', Model2Schema);

function CreateModel1WithStuff(data, cb) {
    if (data.child) { // Save child model first
        data.child = Model2(data.child);
        data.child.save(function(err) {
            cb(err, err ? null : Model1(data));
        });
    } else { // Proceed without dealing with child
        cb(null, Model1(data));
    }
}

CreateModel1WithStuff({
    foo: 'abc',
    child: {
      bar: 'cba'
    }
}, function(err, doc) {
    doc.save();
});
like image 195
Deathspike Avatar answered Oct 14 '22 18:10

Deathspike