-->

Meteor collection.insert callback to return new id

2020-07-31 23:52发布

问题:

I want to get the id of a newly inserted docuement in the callback of meteor.collection.insert.

I insert the Doc as follows:

Meteor.call('createDoc', {
    key1: value1,
    key2: value2
})

The createDoc function looks like that:

Meteor.methods createDoc: (options) ->
    incidents.insert
        key1: options.value1
        key2: options.value2
        , callback(error, result)

callback = (error,result) ->
    console.log result

The Documentation says:

callback Function
Optional. If present, called with an error object as the first argument and,
if no error,the _id as the second.

So I expect result to return the new id, but am getting a Reference Error saying that error and result are not defined. What am I getting wrong here? Any help is much apprecated.

回答1:

BenjaminRH is right about the easier, more likely way to do this. However, there are times when you need the server to do the work, and/or some who insist that is the only way to do database work even in meteor, and here's how your code would do that:

# server code
Meteor.methods createDoc: (options) ->
  created = incidents.insert
    key1: options.value1
    key2: options.value2
  created

# on client code

Meteor.call 'createDoc', info, (err, data) ->
  if err
    console.log JSON.stringify err,null,2
    # DO SOMETHING BETTER!!
  else
    Session.set('added doc', data )  
    # and something reactive in waiting for session to have 'added doc'


回答2:

You mostly have the right idea, but you're confusing a couple of things. Currently, your Meteor method isn't returning anything, because you're calling the insert asynchronously by providing a callback. Asynchronous method returns can be done, but it's a lot more complicated than you need for something this simple (checkout this excellent async guide for more info).

Instead of having a callback, you can use the insert method without a callback and assign that to a variable, like var incidentId = Incidents.insert({ ... }); -- return that.

Then, in the client-side callback for the Meteor.call, the result should be the _id.



回答3:

From client side, your callback function result will return last inserted object id if you return from Meteor.methods.

Meteor.call('addURL', url, function (error, result) {
    urlId = result;
});

Meteor.methods({
    addURL : function(url) {
        return URL.insert(url);
    }
});

urlId has the id of last inserted object.