How do I populate a newly created mongoose Document?
Asked Answered
U

2

6

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));
Ungrateful answered 29/1, 2020 at 3:36 Comment(0)
D
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));
Dunno answered 29/1, 2020 at 6:50 Comment(1)
isn't there a way to populate without searching with findById first?Pickerelweed
C
9

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)
Cohort answered 11/9, 2021 at 9:32 Comment(1)
this should be the accepted answer. except, execPopulate was removed and is no longer necessaryIsothere
D
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));
Dunno answered 29/1, 2020 at 6:50 Comment(1)
isn't there a way to populate without searching with findById first?Pickerelweed

© 2022 - 2024 — McMap. All rights reserved.