Mongoose: Create and then populate?

Created on 19 Feb 2014  路  5Comments  路  Source: Automattic/mongoose

Is it possible to do something like this...?

db.model('User').create({ name: 'John' }).populate('_company').exec(function(err, user) {
    if (err) return next(err)
    console.log(user)
    // outputs user with populate user._company object from Company model
})

The only way I see it working now is...

db.model('User').create({ name: 'John' }, function(err, user) {
  if (err) return next(err)
  db.model('User').findById(user._id).populate('_company').exec(function(err, user) {
    if (err) return next(err)
    console.log(user)
    // outputs user with populate user._company object from Company model
  })
})

All 5 comments

try this

model.findOneAndUpdate({_id:mongoose.Types.ObjectId()}, data, {
    new: true,
    upsert: true,
    runValidators: true,
    setDefaultsOnInsert: true,
    populate: options
})

@TrejGun won't this be slow if there's lot of documents? since it'll check the _id 1 by 1 if mongoose.Types.ObjectId() exists right?

@jericopulvera sure, but you can use Model.populate to populate all the created documents, that will use one query: https://mongoosejs.com/docs/api.html#model_Model.populate

Company.populate(docs, { path: '_company' })

You can also do:

let user = await User.create({ ... })
user = await user.populate('company').execPopulate()

@mienaikoe good suggestion. Here's the relevant docs for posterity:

Was this page helpful?
0 / 5 - 0 ratings