Search code examples
mongodbmongoosesaveref

Saving a document in Mongoose, reference id is not stored in the second document


When I save a new "experience" document with the model Experience, the experience _id is not saved into the document of the user. So my "experiences" array in the user document remains empty. Why?

const mongoose = require('mongoose');

const ExperienceSchema = mongoose.Schema({
  name: String,
  user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
  reviews: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Review' }],
  categories: [{ type: String }],
  });

module.exports = mongoose.model('Experience', ExperienceSchema);

==============================================

const mongoose = require('mongoose');

const UserSchema = mongoose.Schema({
  name: String,
  experiences: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Experience' }],
  });

module.exports = mongoose.model('User', UserSchema);

=============================================

// Update experience to database
router.post('/:id', (req, res, next) => {
  const idexp = req.params.id;

  const newExperience = {
    name: req.body.name,
    user: req.user._id,
  };
  Experience.findOneAndUpdate({ _id: idexp }, newExperience, (err, result) => {
    if (err) {
      return res.render(`/${idexp}/edit`, { errors: newExperience.errors });
    }
    return res.redirect(`/experiences/${idexp}`);
  });
});

Solution

  • Here is the solution... I needed to use $push to update the user document with the experience id before rendering the site.

      Experience.findOneAndUpdate({ _id: idexp }, newExperience, (err, result) => {
        if (err) {
          return res.render('experiences/edit', { errors: newExperience.errors });
        }
        User.findByIdAndUpdate({ _id: req.session.passport.user._id }, { $push: { experiences: idexp } }, (err) => {
          if (err) {
            next(err);
          } else {
            return res.redirect(`/experiences/${idexp}`);
          }
        });
      });