Meteor:我如何保存到集合并从中获取数据

Meteor: How do I save to a collection and getdata out of it?

本文关键字:合并 集合 数据 获取 保存 何保存 Meteor      更新时间:2023-09-26

我正在尝试制作两个函数。Save()应该检查该用户是否有现有文档,如果有,则用新文档更新他的保存,如果没有,则使用用户的唯一id作为文档唯一id插入新文档。Load()应该检查是否存在具有用户Id的现有保存并加载它。我完全是新手,这是我得到的错误

未捕获错误:不允许。不受信任的代码只能更新ID文件[403]

我知道这是因为更新和插入的工作方式。但我想在文档中使用用户唯一的iD,因为它看起来很简单。

function Save() {
        if (Meteor.userId()) {
            player = Session.get("Player");
            var save = {    
                    id: Meteor.userId(),
                    data = "data"
                    };
            console.log(JSON.stringify(save));
                if (Saves.find({id: Meteor.userId()})){
                    Saves.update( {id: Meteor.userId()}, {save: save} )
                    console.log("Updated saves")
                }
                else {
                    Saves.insert(save)
                }
            console.log("Saved");
            }
}
function Load(){
        if (Meteor.userId()){
            if (Saves.find(Meteor.userId())){
                console.log(JSON.stringify(Saves.find(Meteor.userId()).save.player));
                player = Saves.find(Meteor.userId()).save.player;
                data= Saves.find(Meteor.userId()).save.data
            }
        }
}

对象/文档id-字段称为_id。看这里!

当您尝试更新客户端上的现有对象/文档时,会发生错误。您总是需要传入对象_id以从客户端代码更新对象/文档。请注意,您总是试图传递id,而不是_id

所以这样试试吧:

function Save() {
    if (Meteor.userId()) {
        player = Session.get("Player");
        var save = {    
                _id: Meteor.userId(),
                data = "data"
                };
        console.log(JSON.stringify(save));
            if (Saves.find({_id: Meteor.userId()})){
                Saves.update( {_id: Meteor.userId()}, {save: save} )
                console.log("Updated saves")
            }
            else {
                Saves.insert(save)
            }
        console.log("Saved");
        }
}

还要注意,Load()函数可以工作,因为Collection.find()使用您作为文档的_id传递的字符串。

希望有帮助!