alex.mironov
alex.mironov

Reputation: 2942

Mongoose - get _id of a newly saved inner record

There is a Mongoose Schema with sub-documents. I want to be able to push sub-document and process newly created inner item after parent saving.

Is there any easy way to get an _id of a newly created inner item? Here is the code:

var trackSchema = mongoose.Schema({
  title: String
});
var userSchema = mongoose.Schema({
  displayName: String,
  tracks: [trackSchema]
});

var Track = mongoose.model('Track', trackSchema);
var User = mongoose.model('User', userSchema);

var track = new Track({
  title: 'Sunrise'
});

user.tracks.push(track); // assume 'user' was returned by User.findById()

user.save(function (err, userUpdated) {

  // ... is there any way to find _id of pushed 'track' ???

});

Upvotes: 1

Views: 68

Answers (1)

Andrei Beziazychnyi
Andrei Beziazychnyi

Reputation: 2917

Easiest way is to create ObjectId in code and assign it to _id property of inner item on object creation

Upvotes: 1

Related Questions