1

I want to update my data by using id but all the time i am not able to update it. It is even not giving any error and storing null values

router.put('/special/:id', function(req, res) {

    User.findByIdAndUpdate(req.params.id, {

        $set: {email: req.body.email, password: req.body.password}
    },
    {

        new: true,
        useFindAndModify: false
    },
    function(err, updatedData) {

        if(err) {

            res.send('Error updating');
        } else {

            res.json(updatedData);
        }
    });
});
1
  • We would need to see your User.findByIdAndUpdate function Commented Jul 18, 2019 at 17:27

1 Answer 1

1

Try rewriting it using async, and make sure your Mongoose schema is correct as well. So your mongoose model should be a seperate file called 'userModel.js'.

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

var userSchema = new Schema ({
    email: String,
    password: String,

});

let User = module.exports = mongoose.model('User', userSchema);

Then in your app.js. Have:

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const port = 3000;
const bodyParser = require('body-parser');

//Body Parser Middleware
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

//connect to db
mongoose.connect('mongodb://localhost:27017/YOUR_DB_NAME_HERE',{useNewUrlParser: true})
let db = mongoose.connection;
//check db connection 
db.once('open', function() {
    console.log('Connected to ' + db.name)
})
//check for db error
db.on('error', function(err) {
    console.log(err);
})

//Starting App (on localhost:3000)
app.listen(port, function() {
    console.log('Server started on port ' + port);
});

Note: Once you start the app. In your node console if you are not seeing a message saying 'Connected to {YOUR DB NAME}'. Then either you don't have mongoDB running or you don't have it installed. So first you want to make a new console window and type:

mongod

This should work, and if its already running you should see a message at the bottom saying:

2019-07-19T12:17:37.716+1000 E STORAGE  [initandlisten] Failed to set up listener: SocketException: Address already in use

Now once you figure this out. And you've found that your connection to mongoDB is good. You want to redo your PUT route to make an async request as follows.

Note: Before the route, you need to require your model so mongoose can update records for you.

//Requiring your shop model
const User = require('./models/userModel')
app.put('/special/:id', async function(req, res){

      const id = req.params.id

      //Making a user object to parse to the update function
      let updatedUser = {}
      updatedUser.email = req.body.email
      updatedUser.password = req.body.password

      await User.findByIdAndUpdate(id, updatedUser, function(err, updatedData){
             if(err){
                      console.log(err)
          }
             else {
                      console.log(updatedData)
                      //res.redirect or res.send whatever you want to do
         }
      })



})


Sign up to request clarification or add additional context in comments.

Comments

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.