Reputation: 319
I am trying to create "server side function" (custom JS function loaded in Mongo db) according to autoincrement tutorial. The main idea is to have function getNextSequence(collectionName), which returns autoincrement id for this collection. Trick is to have separate collection "counters" with document for each collection, that holds autoincrement status.
Anyway, I have created and loaded that function in Mongo and it works nicely via Mongo shell:
db.users.insert(
{
_id: getNextSequence("userid"),
name: "Sarah C."
}
)
It also works from NodeJS via eval:
db.eval('getNextSequence(\'test\')', function(err, result){...});
But I can't figur out, how to use it inline in document when inserting from NodeJS. I cannot write:
{
_id: getNextSequence("userid"),
name: "Sarah C."
}
as this would expect getNextSequence to be NodeJs method. Is there any expression form in NodeJS+MongoDB for this? Thanks!
Upvotes: 1
Views: 1924
Reputation: 1905
You'll need to call it in node the way you have specified above and then use the value that is returned in your insertion.
db.eval('getNextSequence(\'test\')', function(err, result) {
db.users.insert({
_id: result,
name: "John Doe"
...
}, function(err, result) {
...
}})
});
For cleaner syntax, you could try using the npm package mongo-triggers:
https://www.npmjs.org/package/mongo-triggers
Upvotes: 1
Reputation: 177
in the post method set a variable which requires db:
var db = req.db;
Then declare a variable for your db collection:
var collection = db.get('counter');
then insert your items:
collection.insert({ _id: getNextSequence("userid"), name: "Sarah C." }, function (err, doc) { if (err) { // DO SOMETHING } else { // DO SOMETHING } });
Upvotes: 1