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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With