Goteii
Goteii

Reputation: 170

Problem with a Cast using Router.put with mongoDB in MERN app

I want to attach the router.put which will update the Boolean(isOn) in toggle button but firstly I wanted to try how it works and now I am facing the problem.

const express = require("express");
const router = express.Router();
const Buttons = require('../../models/Buttons');

// GET buttons
// This request works perfect
router.get('/', (req,res) => {
 Buttons.find()
.sort({name: 1})
.then(buttons => res.json(buttons))
});

// PUT buttons
// This one doesnt work at all
router.put('/:name', function(req,res,next) {
    Buttons.findByIdAndUpdate({name: req.params.name},         
 req.body).then(function(){
    Buttons.findOne({name: req.params.name}).then(function(buttons){
        res.send(buttons);
    });
});
 });

 module.exports = router;

Model of buttons has only name: String, required: true and isOn: Boolean, required: true and data in db looks like that:

enter image description here

Can you tell me what did I do wrong here?

Code of Buttons modal :

const mongoose = require('mongoose');
const Schema = mongoose.Schema

const buttonSchema = new Schema ({
name: {
type: String,
required: true
},
isOn: {
type: Boolean,
required: true
}
});

 module.exports = Buttons = mongoose.model("buttons", buttonSchema);

Upvotes: 0

Views: 74

Answers (2)

Sarfraaz
Sarfraaz

Reputation: 1269

You ca only use findByIdAndUpdate when you want to update the document by matching the _id of the document

If you want to match the document by any other property (such as name in your case), you can use findOneAndUpdate

Write your query like this

router.put('/:name', function(req,res,next) {
    Buttons.findOneAndUpdate({name: req.params.name},         
 req.body).then(function(){
    Buttons.findOne({name: req.params.name}).then(function(buttons){
        res.send(buttons);
    });
});
 });

Hope this helps

Upvotes: 1

Prakash Karena
Prakash Karena

Reputation: 2605

Please add your id as well which you have to update in your database

Model.findByIdAndUpdate(id, updateObj, {new: true}, function(err, model) {...

This error occur because findByIdAndUpdate need id of an Object which we want to update so it shows ObjectId error. so pass your id from front end and use it in your back-end to update particulate data.

step 1 : you can create new endpoint for update-name

router.put('/update-name', function(req,res,next) {
  //here you can access req.body data comes from front-end
 // id = req.body.id and name = req.body.name then use it in your 
 Buttons.findByIdAndUpdate(id, { name : name }, {new: true}, function(err, model) {...

}

step 2 : try this endpoint /update-name and pass your data in Body from postman

Upvotes: 0

Related Questions