Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push value in array of mongodb document

i have one mongodb collection which have documents like these enter image description here

now I want to push a value to rooms array of a document where email is [email protected] .... I have made this controller in node js.

module.exports.createroom = async (req,res) => {
    const {roomid,email} = req.body;
    UserModel.updateOne(
        { email: email },
        {
          $push: { rooms: roomid}
        }
     )
     res.send('done')
    
}

user schema

const mongoose = require("mongoose")
const userSchema = new mongoose.Schema({
    email:{
        type:String,
        require:true
    },
    password:{
        type:String,
        require:true
    },
    rooms:{
        type:Array
 }

})

module.exports = mongoose.model("User",userSchema);

correct syntax for updating the record.

like image 965
Geekyvinayak Avatar asked Aug 09 '26 14:08

Geekyvinayak


1 Answers

Make changes in your controller..

module.exports.createroom = async (req,res) => {
    const {roomid,email} = req.body;
    const user = await UserModel.findOneAndUpdate(
        { email : email },
        { $push: { rooms: roomid }  },
      )
    res.send("done")
}
like image 58
MihirBangia Avatar answered Aug 11 '26 04:08

MihirBangia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!