DanPhelps
DanPhelps

Reputation: 53

update function javascript and mongodb

Im building my own web app and I'm struggling on how to replace a previous added note. So far the add jquery using nodejs and express works, so I can see my note added to the mongodb. however I created a replace button which doesn't replace the previous note but only add it on the database. The delete button works fine.
Here is the code which I believe might have some problems looking up which database to look on. Im replacing a previous note (name, note) with a preset one (Dan, new note). All my output is displayed with a .ejs file which works fine( update, add notes all based on mlab database). Thanks in advance.

update.addEventListener('click', function () {
  fetch('/notes', {
    method: 'put',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({
      'name': 'Dan',
      'quote': 'new note'
    })
  }).then(response => {
    if (response.ok) return response.json()
  }).then(data => {
    console.log(data)
  })
})

Upvotes: 1

Views: 64

Answers (1)

Jan Steuer
Jan Steuer

Reputation: 151

You need to identify which entity you want to update. I guess that when you're deleting a note you're sending sth like this:

fetch('/notes/ID', {method: 'delete'})

When you want to update an entity you need to do it similarly:

fetch('/notes/ID', {
    method: 'put',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({
      'name': 'Dan',
      'quote': 'new note'
    })

(Replace ID with a real _id of the mongo entity)

Upvotes: 1

Related Questions