Isak La Fleur
Isak La Fleur

Reputation: 4668

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

Upvotes: 0

Views: 1134

Answers (2)

Isak La Fleur
Isak La Fleur

Reputation: 4668

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

Upvotes: 0

notionquest
notionquest

Reputation: 39186

The experiences is the sub-document of user schema. So, when you save experiences, the user will not be saved. However, when you save user, the experience should be saved.

Refer this subdocs documentation

Upvotes: 1

Related Questions