How do I populate a newly created mongoose Document?

3.3k Views Asked by At

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));
2

There are 2 best solutions below

1
SuleymanSah On BEST ANSWER

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));
1
MANAN On

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','dishes'])
res.setHeader('Content-Type', 'application/json').status(200).json(favourite)