5

I have a case where I am checking whether a document already exists and if it does not exists I am creating a new document. I need to populate 2 fields inside the document. My problem is that the .populate method is not supported on the .create method as I get an error if I try to do that. Furthermore, the .populate method is not working on the returned document as well. How do I correctly populate a newly created document ? Here is my code :

Favorite.create({ user: req.user._id, dishes: req.params.dishId })
                    .then((favorite) => {
                        favorite.populate('user');
                        favorite.populate('dishes');
                        console.log('Favorite marked', favorite);
                        res.statusCode = 200;
                        res.setHeader('Content-Type', 'application/json');
                        res.json(favorite);
                    }, (err) => next(err))
            }
        })
        .catch((err) => next(err));
Harsha Limaye
  • 915
  • 9
  • 29

2 Answers2

7

You are querying the document twice in the above solution which will take time and is operation heavy. So instead we can populate the same document this way

let favourite = await Favourite.create({ options })
favourite = await favourite.populate('user').populate('dishes').execPopulate()
res.setHeader('Content-Type', 'application/json').status(200).json(favourite)
MANAN
  • 713
  • 9
  • 6
  • 4
    this should be the accepted answer. except, `execPopulate` was [removed](https://mongoosejs.com/docs/migrating_to_6.html#removed-execpopulate) and is no longer necessary – vch Jul 19 '22 at 14:49
2

You can use the populate method after Model.find methods.

Created favorite will have _id value, so you can find the favorite by _id, and then populate user and dishes like this:

Favorite.findById(favorite._id)
          .populate("user")
          .populate("dishes")

All code:

  Favorite.create({ user: req.user._id, dishes: req.params.dishId })
    .then(
      favorite => {
        console.log("Favorite marked", favorite);
        const result = Favorite.findById(favorite._id)
          .populate("user")
          .populate("dishes");

        res.statusCode = 200;
        res.setHeader("Content-Type", "application/json");
        res.json(result);
      },
      err => next(err)
    )
    .catch(err => next(err));
SuleymanSah
  • 17,153
  • 5
  • 33
  • 54