取回更新后的对象 mlab api PUT

Getting back updated object mlab api PUT

我正在尝试使用 mlab api 到 ajax 修改对象 call.Following 是使用的代码:

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)
})

对象获取成功updated.The我收到的响应只是被修改的对象的数量,而不是被修改的对象本身。 如何在不进行往返的情况下获取修改后的对象?

对 mLab 数据 API 的 PUT 请求将 运行 MongoDB 的 update 命令。 update 命令不能 return 更新对象 (see the documentation here).

但是您可以通过发布到 mLab 数据 API 的 /databases/<dbname>/runCommand 端点来 运行 MongoDB 的 findAndModify 命令。 See the documentation for the runCommand endpoint here.

findAndModify 能够 return 更新对象。 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 更新单个文档,默认行为是更新的文档将被 returned。参见 the documentation for updating single documents here