在 Mongoose 中保存文档,引用 ID 未存储在第二个文档中

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

当我用模型体验保存一个新的 "experience" 文档时,体验 _id 没有保存到用户的文档中。所以我在用户文档中的 "experiences" 数组仍然是空的。为什么?

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

experiencesuser 架构的子文档。因此,当您保存 experiences 时,user 将不会被保存。但是,当您保存 user 时,应该保存 experience

Refer this subdocs documentation

这是解决方案...我需要使用 $push 在呈现网站之前使用体验 ID 更新用户文档。

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