-1

I am trying to modify object using mlab api through ajax call.Following is the code used:

query="{'email':'"+localStorage.getItem("email") +"','restore':'yes'}"
object={"$set":{'restore':"no"}}
$.ajax({

url: "https://api.mongolab.com/api/1/databases/db/collections/coll?apiKey=apiKey&q="+query,
data: JSON.stringify( object ),
type: "PUT",

contentType: "application/json"
}).done(function( restored_obj ) {
console.log(restored_obj)
})

The object gets successfully updated.The response that I receive is only the number of objects that are modified and not the modified object itself. How do I get modified objects without making a round trip?

1 Answers1

1

A PUT request to the mLab Data API will run MongoDB's update command. The update command cannot return the updated object (see the documentation here).

But you can run MongoDB's findAndModify command by posting to the /databases/<dbname>/runCommand endpoint of the mLab Data API. See the documentation for the runCommand endpoint here.

findAndModify is able to return updated objects. See the documentation here. If you set the new option to true, you will receive the newly updated document rather than the old document.

Your code should look something like this:

query = {
    email: localStorage.getItem("email"),
    restore: 'yes'
}

object = {
    findAndModify: '<collection>' // use your own collection name
    query: query,
    update: {
        $set: {
            restore: "no"
        }
    },
    new: true
}

$.ajax({
    url: "https://api.mongolab.com/api/1/databases/db/runCommand?apiKey=apiKey",
    data: JSON.stringify(object),
    type: "POST",
    contentType: "application/json"
}).done(function(restored_obj) {
    console.log(restored_obj)
})

Also, if you ever want to make an update to a single document by _id, the default behavior is that the updated document will be returned. See the documentation for updating single documents here.

tfogo
  • 1,416
  • 1
  • 14
  • 23