2017-05-05 41 views
0

当我使用模型体验保存新的“体验”文档时,体验_id未保存到用户的文档中。所以我在用户文档中的“体验”数组仍然是空的。为什么?在Mongoose中保存文档时,引用标识未存储在第二个文档中

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

回答

0

下面是解...我需要使用$推渲染网站之前更新与经验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}`); 
     } 
    }); 
    });