plrbr
plrbr

Reputation: 23

(mongoose) put method does not work

I am creating web API using mongoose.

POST and GET work, but I have no idea how to implement PUT method in mongoose.

Here is what I created:

board.js

const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const config = require('../config/database');

const BoardSchema = mongoose.Schema({
    _id: {
        type: String
    },
    position: {
        type: [String]
    }
});

const Board = module.exports = mongoose.model('boards', BoardSchema);

module.exports.getBoardById = function (id, callback)
{
    Board.findById(id, callback);
}

module.exports.addBoard = function (newBoard, callback)
{
    newBoard.save(callback);
}

module.exports.updateBoard = function (newBoard, callback)
{
    newBoard.save(callback);
}

users.js

router.put('/board/:id', (req, res, next) =>
{
    let newBoard = new Board({
        _id: req.params.id,
        position: req.body.position
    });

    Board.updateBoard(newBoard, (err, board) =>
    {
        if (err)
        {
            res.json({ newBoard: newBoard, success: false, msg: "Failed to update board" });
        }
        else
        {
            res.json({ newBoard: newBoard, success: true, msg: "Board added" });
        }
    });
});;

Here, in the board.js, I created methods for adding a new board and updating to existing board. .addBoard is working correctly and am able to test it using Postman. But, .updateBoard adds the data when the data does not exist, but does not update any data and returns false as response (just like POST does). Is there any way I can make the PUT method works?

Thank you!

Upvotes: 0

Views: 11157

Answers (3)

pr0p
pr0p

Reputation: 2358

As you are using req.body i think you are trying to call a put request from a form (sometimes happens with AJAX requests also). For doing that use method-overide. And set the xhr header as given in the documentation. This will surely work.

Upvotes: 0

SAGAR RAVAL
SAGAR RAVAL

Reputation: 319

why are you using save method while updating?

const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const config = require('../config/database');

const BoardSchema = mongoose.Schema({
    _id: {
        type: String
    },
    position: {
        type: [String]
    }
});

const Board = module.exports = mongoose.model('boards', BoardSchema);

module.exports.getBoardById = function (id, callback)
{
    Board.findById(id, callback);
}

module.exports.addBoard = function (newBoard, callback)
{
    newBoard.save(callback);
}

module.exports.updateBoard = function (condition, update, callback)
{
    Board.update(condition,update,callback);
}

in controller

router.put('/board/:id', (req, res, next) =>
{
    let newBoard = new Board({
        _id: req.params.id,
        position: req.body.position
    });

    Board.updateBoard({ _id: req.params.id } ,newBoard, (err, board) =>
    {
        if (err)
        {
            res.json({ newBoard: newBoard, success: false, msg: "Failed to update board" });
        }
        else
        {
            res.json({ newBoard: newBoard, success: true, msg: "Board added" });
        }
    });
});

try this.

Upvotes: 1

Joseph Chambers
Joseph Chambers

Reputation: 4068

Please let me know if this works for you! I want to introduce you to http://mongoosejs.com/docs/api.html#findbyidandupdate_findByIdAndUpdate

router.put('/board/:id', (req, res) => {
  const {id: _id} = req.params // Assigning id to _id which is a es6 feature. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
  const {position} = req.body

  const newBoard = {
    _id,
    position
  }

  Board.findByIdAndUpdate(
    _id,
    newBoard,
    (err, updatedBoard) => {
      if (err) {
        res.json({
          newBoard,
          success: false,
          msg: 'Failed to update board'
        })
      } else {
        res.json({newBoard, success: true, msg: 'Board added'})
      }
    }
  )
})

Upvotes: 3

Related Questions