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