0
votes

hello im new to nodejs and mongoose. im working on my web application and im trying to make mongoose findByIdAndUpdate which doesnt update my mongoDB, what am i doing wrong? im trying to update an exciting user details.

i tried many solutions to this problems like many querys but none of them work. im making post request with postman trying to change this fields : firstName lastName username email phone to the route : http://localhost:5000/api/users/5cbb60157b07f13ec88070c4

but im always getting the old user and not the updated user as response

api/users :
const express = require('express');
const router = express.Router();
const User = require('../../models/User');
const bcrypt = require('bcryptjs');
const validateCreateUserInput = require('../../validation/createUser');
const passport = require('passport');

router.post('/:id', passport.authenticate('jwt', { session: false }), (req, res) => {
  const userDetails = {};
  if (req.body.firstName) userDetails.firstName = req.body.firstName;
  if (req.body.lastName) userDetails.lastName = req.body.lastName;
  if (req.body.username) userDetails.username = req.body.username;
  if (req.body.email) userDetails.email = req.body.email;
  if (req.body.phone) userDetails.phone = req.body.phone;
  User.findByIdAndUpdate(
    { _id: req.params.id },
    { new: true },
    { $set: userDetails })
    .then(user => {
      res.json(user)
    })
    .catch(err => console.log(err));
})

module.exports = router;

User model :

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

const UserSchema = new Schema({
  firstName: {
    type: String,
    required: true
  },
  lastName: {
    type: String,
    required: true
  },
  username: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  phone: {
    type: String,
    required: true
  },
  createdAt: {
    type: Date,
    default: Date.now
  },
  updatedAt: {
    type: Date,
    default: Date.now
  }
})

module.exports = User = mongoose.model('users', UserSchema);

i expect the data to change in the mongoDB

2

2 Answers

1
votes

It will work if you change the code as follows. The "$set" statement used in the Mongodb Shell operation is not used with "Mongoose".

 User.findByIdAndUpdate(
  { _id: req.params.id },
  userDetails,
  { new: true })
 .then(user => {
  res.json(user)
  })
 .catch(err => console.log(err));
  })
0
votes

You can use 'update' method when you use $set. Example:

User.update({
_id: Schema.Types.ObjectId(req.params.id)
},{
Key: value
})