mongoosepromisemongoose-schemamongoose-populate

How do I populate a newly created mongoose Document?


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

Solution

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