Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I can see several ways to do so.</p> <p><strong>First</strong>, you may store <code>last_id</code> in a global variable:</p> <pre><code>var last_id = 0; app.post('/app/new', function (req, res) { var newApp = app.db.models.userApp({ appid: ++last_id, appname: req.param('appname'), appdesc: req.param('appdesc') }); newApp.save(); }); </code></pre> <p>You may add a proper initialization of <code>last_id</code>, so it'll "catch up" with your database when your application starts.</p> <p>The only disadvantage of this approach is that you can't use it if you have several <code>node.js</code> processes.</p> <p><strong>Second</strong>, you may query your database each time you want to create new document:</p> <pre><code>app.post('/app/new', function (req, res, next) { app.db.models.userApp.find() .sort({_id: -1}) .limit(1) .select('_id') .exec(function (err, docs) { if (err) return next(err); var newApp = app.db.models.userApp({ appid: docs[0]._id, appname: req.param('appname'), appdesc: req.param('appdesc') }); newApp.save(); }) }); </code></pre> <p>But there is no way to guarantee that the next <code>find</code> operation will occur after the previous <code>save</code> operation. So, there is a chance that your app will try two save two different docs with one <code>_id</code>. It's why you should avoid this solution if possible.</p> <p><strong>Third</strong>, you may use some other storage (e.g. Redis) to atomically increment <code>last_id</code> every time you're reading it:</p> <pre><code>var RedisClient = require('redis').createClient() app.post('/app/new', function (req, res, next) { RedisClient.incr('last_id', function (err, next_id) { if (err) return next(err); var newApp = app.db.models.userApp({ appid: next_id, appname: req.param('appname'), appdesc: req.param('appdesc') }); newApp.save(); }) }); </code></pre> <p>This solution is the best one, but it require additional database to be installed.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload