Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check Collections.insert() is Successfully Inserted or not in Meteor?

How to check(user created collections) Collections.insert() is Successfully Inserted or not in Meteor JS?. For example I am using the Client Collections to insert details as shown below:

Client.insert({ name: "xyz", userid: "1", care:"health" });

How to know the above insert query is successfully inserted or not?. Because of the below problem

 If the form details are successfully inserted  - do one action
  else -another action

So Please suggest me what to do?

like image 990
user3213821 Avatar asked Feb 10 '14 08:02

user3213821


2 Answers

Insert provides a server response in the arguments to a callback function. It provides two arguments 'error' and 'result' but one of them will always be null depending on whether the insert is successful.

Client.insert( { name: "xyz", userid: "1", care:"health" }
  , function( error, result) { 
    if ( error ) console.log ( error ); //info about what went wrong
    if ( result ) console.log ( result ); //the _id of new object if successful
  }
);

See documentation for more info.

like image 94
user728291 Avatar answered Nov 14 '22 07:11

user728291


In addition to user728291's answer that uses a callback, on the server, you can also do:

var value = Collection.insert({foo: bar});

which will return the _id of the inserted record on success (executions is blocked until the db acknowledges the write). You will have to handle a possible error in a try...catch, but sometimes callbacks are just a bit, cumbersome :)

So this should also work on the server:

try {
    var inserted = Collection.insert({foo: bar});
} 
catch (error) {
    console.log("Could not insert due to " + error);
}

if (inserted)
    console.log("The inserted record has _id: " + inserted);

Thank you @user728291 for the clarification.

like image 23
jeroentbt Avatar answered Nov 14 '22 09:11

jeroentbt