Search code examples
node.jsmongodbmongooseref

Save _id current logged inuser to another mongodb collection


I want to save the user collection _id from the currently logged in user to the projects collection when a new project is saved to the database. The project gets saved but the createdby field isn't in the db after saving. I've followed this example: https://mongoosejs.com/docs/2.7.x/docs/populate.html I found this to be the right way for referencing in several examples .

What am I missing?

project model

 const mongoose = require('mongoose');

    const projectSchema = new mongoose.Schema({
        projectTitle:{
            type:String,
            required: true
        },
        createdBy: {
            type: mongoose.Schema.Types.ObjectId, 
            ref: 'Users' ,
        },
         createdAt: {
            type: Date,
            default: Date.now,
            required: true
        },
    });

    module.exports = mongoose.model('Projects', projectSchema)

route post project form

// @desc    Process project add form
// @route   POST /project
router.post('/', ensureAuth, async (req, res) => {
    req.body.user = req.user.id
    await Project.create(req.body)
    res.redirect('/')
    })

Solution

  • Though not fully clear from your code snippets, my guess is you lack this piece of code in the controller:

    // @desc    Process project add form
    // @route   POST /project
    router.post('/', ensureAuth, async (req, res) => {
        req.body.user = req.user.id // not sure if this is necessary?
        req.body.createdBy = req.user._id
        await Project.create(req.body)
        res.redirect('/')
        })
    

    When using mongoose.Schema.Types.ObjectId, .id is just a getter method that returns a string representation of the ObjectId (so basically ._id.toString()). To properly save the reference, you should save the ._id of the User document (i'm assuming in my code that req.user holds the full document so you can access the ObjectId).