javascript - Node and Mongoose create/use field that increases +1 for each new added -
i'm going try , keep simple possible. i've spent day testing modules this, , @ point have gotten confused figured best option.
i have schema:
var appschema = new mongoose.schema({ appid: { type: number }, appname: { type: string }, appdesc: { type: string } }); app.db.model('userapp', appschema); using express , processing post, want create "a new app"
app.post('/app/new', function (req, res) { var newapp = app.db.models.userapp({ appid: functiontoincreasebyone(), appname: req.param('appname'), appdesc: req.param('appdesc') }); newapp.save(); }); i removed of bloat in there, redirects, etc, keep simple. have appid set @ 1 first first app added, , increase +1 each new app added. seems simple i've gone through many complex examples head hurts now.
i thought using .find , orderby find app highest appid, use , add +1 it, i'm sure there has another, easier way. don't want appid change when there update, time want set on first post route create new app.
if please me out here or @ least point me in right direction, appreciate it.
i can see several ways so.
first, may store last_id in global variable:
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(); }); you may add proper initialization of last_id, it'll "catch up" database when application starts.
the disadvantage of approach can't use if have several node.js processes.
second, may query database each time want create new document:
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(); }) }); but there no way guarantee next find operation occur after previous save operation. so, there chance app try 2 save 2 different docs 1 _id. it's why should avoid solution if possible.
third, may use other storage (e.g. redis) atomically increment last_id every time you're reading it:
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(); }) }); this solution best one, require additional database installed.
Comments
Post a Comment