1

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.

1
  • you can write {username:username} as just {username} , see MDN for details Commented Jun 17, 2021 at 14:14

1 Answer 1

0

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
                }
            }
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for answering. But, I want to update data by using a username instead of _id.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.