Aaron Shen
Aaron Shen

Reputation: 8374

How to automatically create a referenced child doc when the parent doc is created?

I have models like below:

var GameSchema = new Schema({
    players: [{type: Schema.Types.ObjectId, ref: 'Player'}], 
});

var PlayerSchema = new Schema({
    name: {
        type: String,
        required: true
    }
});
mongoose.model('Player', PlayerSchema); 
mongoose.model('Game', GameSchema); 

Here's my code:

var p1 = new Player({name: 'abc'});
var p2 = new Player({name: 'def'});
var agame = new Game({players:[p1,p2]});
agame.save();

What I'm trying to do is when the new game is created in db, the p1, p2 player should also be created. my code doesn't work, p1,p2 is not saved. How can I achieve that?

Upvotes: 0

Views: 377

Answers (3)

Ewertom Moraes
Ewertom Moraes

Reputation: 121

In my case, I have to do this also manually. As it is a web application, then in my parent controller it got something like

.post((req, res) => {
    let parent = req.body;
    if(parent && parent.childrenArray){
        let ids = [];
        parent.childrenArray.forEach((children)=>{
            let c = new Children(children);
            c.save();
            ids.push(c._id);
        })
        parent.childrenArray = ids;
        req.body = parent;
    }

    // create parent
})

Upvotes: 0

JohnnyHK
JohnnyHK

Reputation: 311955

players is an array of ObjectIds, so you need to pass in the _id of p1 and p2 instead of the whole object. A new model's _id field is populated during new, so it's available right away, but you still need to call save on all three.

var p1 = new Player({name: 'abc'});
var p2 = new Player({name: 'def'});
var agame = new Game({players: [p1._id, p2._id]});
p1.save();
p2.save();
agame.save();

Upvotes: 2

Jayram
Jayram

Reputation: 19578

This you will need to do manually. First save the players and get their Object ID's. Push into the referenced parent players array. Next step is to save the Parent.

Upvotes: 2

Related Questions