Rahul Maurya
Rahul Maurya

Reputation: 19

How Can I insert Data into MongoDB DB Through An POST-API?

I want to search the user through their username and insert the movie & review(they're in movies field) it into the document.

The structure of my schema is like this : const userschema=new mongoose.Schema({

    name:{
        type:String,
        minlength:3

    },
    
    username:{
        type:String,
        minlength:3

    },

    password:{
        type:String,
    },

    token:{
        type:String
    },
    
    movies:[{
        
        movie:{
            type:String
        },
        review:{
            type:String
        },
        rating:{
            type:String
        }
    }
    ],

    invites:[{
        type:String,
    }],

    favourites:[{

        movie_name:{
            type:String
        }
    }]

})

What I have done till now: app.post("/review", async(req,res)=>{

const{movie, review, username}=req.body;

if(!movie || !review || !username){             //check if details entered or not
    return res.json({error:"Enter all details"});
}

try{
    const userexist = await signup.findOne({username:username});  //searching user by username 
    if(userexist){
        const result = await signup.findOneAndUpdate({username:username}, { 
            $set: {
                movie:req.body.movie,         
                review: req.body.review}
            }, {
                new: true
            });
        const resu=await result.save();
        res.status(201).send(resu);       
    } 
}
catch(e){
    console.log(e);
    res.status(400).send(e);
}

})

Please help me to insert movie & review into the database(into movies field) without changing the existing schema.

Upvotes: 1

Views: 847

Answers (1)

Arpit
Arpit

Reputation: 539

you could do something like this. make a function to update the user. then if the user exists, i.e. if there is a result then, push it into the movies array.

    let updateUser => {
        if(result) {
        UserModel.findByIdAndUpdate({
            _id: req.body.id
        },
    {
            $push: {
                movies: {
                    movie: req.body.movies
                    review: req.body.review
                }
            }
    }

Upvotes: 0

Related Questions