简体   繁体   中英

Update data in MongoDB using Mongoose and Node.js

I am trying to update certain info in a user collection, when the user is visiting a page.

But my method doesn't work. Can anyone help to get it fixed.

app.get('/add-your-accommodation/apartment-type', (req, res, next) => {

  if (req.isAuthenticated()) {
    res.render('apartment-type.ejs')
  } else {
    res.render('login.ejs')
  }

  var id = req.params.id

  if(mongoose.Types.ObjectId.isValid(id)) {
     User.findByIdAndUpdate(id, {$set: {accomtype: 'house'}},{new: true})   
  }
});

Try findOneAndUpdate . Also, use callback in your query function for getting the error or result.


app.get('/add-your-accommodation/apartment-type/:id', (req, res, next) => {
    if (req.isAuthenticated()) {
        res.render('apartment-type.ejs')
    } else {
        res.render('login.ejs')
    }
    var id = req.params.id

    if(mongoose.Types.ObjectId.isValid(id)) {
        User.findOneAndUpdate({_id: mongoose.Types.ObjectId(id)}, { $set: { accomtype:'house' } },(err, result)=>{
            if (err) throw new Error(err);
            console.log(result)
            return
        })   
    }   
});

Your req.params.id is undefined since there is no mention of it in the route path. You can do this,

app.get('/add-your-accommodation/apartment-type', (req, res) => {

  if (!req.isAuthenticated()) {
    return res.render('login.ejs')
  }

  res.render('apartment-type.ejs')

  var id = req.user._id //since you're using passport (LocalStrategy)

  if(mongoose.Types.ObjectId.isValid(id)) {
     User.findByIdAndUpdate(id, {$set: {accomtype: 'house'}})
  }
})

Now when you call your API, do it like this,

GET /add-your-accommodation/apartment-type

I agree with @kedar-sedai, when you update/change something in your DB, you should not use a GET request. A good practise would be to use the PUT method, even if you have nothing to pass in the body. It makes it easier for you and other developers to understand what your code does at a glance.

Here are 4 HTTP requests that will work in most of the use cases :

GET

You want to retrieve information from your DB (ex: get users, get all the apartment types...)

POST

You want to add information (ex: register user, add an apartment, ...), or send information using the body of the POST request (ex: login, ...)

PUT

You want to update a value (ex: change username, change an apartment type, ...)

DELETE

You simply want to delete something in your DB (ex: delete a user...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM