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();
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With