使用Mongoose保存文档时,引用ID不会存储在第二个文档中

时间:2017-05-05 17:52:01

标签: mongodb mongoose save ref

当我保存新的"体验"具有模型体验的文档,体验_id不会保存到用户的文档中。所以我的经历"用户文档中的数组保持为空。为什么呢?

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

============================================== < / p>

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

1 个答案:

答案 0 :(得分:1)

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

Refer this subdocs documentation