meteor-collection-hooks
meteor-collection-hooks copied to clipboard
Problem with generating _id in before.insert hook
I want to change the _id of a document in a before.insert hook.
The document with the changed id is correctly inserted into the collection, but the return value of the insert
call still is the original id. Even when using the callback to insert
on the server there is no way to get the generated id. This way the caller is unable to find out the id of the newly inserted document.
Example:
Stuff.before.insert(function (userId, doc) {
console.log("original id:", doc._id);
doc._id = "12345";
console.log("inserted id:", doc._id);
});
var id = Stuff.insert(doc, function(err, result) {
if (err) return console.log("insert error:", err);
console.log("callback id:", result);
});
console.log("returned id:", id);
The output then is:
original id: B57zZpKtMn67fnN9r
inserted id: 12345
returned id: B57zZpKtMn67fnN9r
callback id: B57zZpKtMn67fnN9r
Interesting... I'm on the fence but leaning towards implementing something that checks the doc._id for changes and then passing that back. I'll think more on it but i think the behavior you're asking for makes sense.
Thanks for the response!
To give a little more background: I was trying to keep the collection in sync with an SQL table. The idea was to insert the documents into the SQL table in the before.insert hook and set the ID to the one generated on the SQL side. That actually worked great, until I found out that it's impossible to find out the new ID.
I have the same problem. How to solve? Please example.