简体   繁体   中英

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

I am trying to make two function. Save() should check if there is an existing document for that user, and if there is then update his save with a new one, and if there is not then insert a new doc using the user's unique id as the docs unique id. Load() should check if there is an existing save with the user's Id and load it. I am purely new to that and here is the error I get

Uncaught Error: Not permitted. Untrusted code may only update documents by ID. [403]

I get that it happens because of how update and insert work. But I want to use the user's unique iD for documents, because it looks simple.

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

            }
        }
}

Objects/documents id -field is called _id . See here!

The error occurs when you try the update of the existing object/document on the client side. You always need to pass in the objects _id to update the object/document from client code. Note that you always try to pass an id not an _id !

So try it like this:

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

Also note that your Load() function could work, because Collection.find() uses the string you pass as an _id for the document.

Hope that helped!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM