我试图通过ajax调用使用mlab api修改对象。以下是使用的代码:
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)
})
对象成功更新。我收到的响应只是修改的对象数,而不是修改后的对象本身。 如何在不进行往返的情况下获得修改过的对象?
答案 0 :(得分:1)
对mLab Data API的PUT请求将运行MongoDB的update
命令。 update
命令无法返回更新的对象(see the documentation here)。
但您可以通过发布到mLab Data API的findAndModify
端点来运行MongoDB的/databases/<dbname>/runCommand
命令。 See the documentation for the runCommand
endpoint here
findAndModify
能够返回更新的对象。 See the documentation here。如果您将new
选项设置为true
,您将收到新更新的文档而不是旧文档。
您的代码应如下所示:
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)
})
此外,如果您希望按_id
对单个文档进行更新,则默认行为是将返回更新的文档。请参阅the documentation for updating single documents here。