Create unique autoincrement field with mongoose [duplicate]

const ModelIncrementSchema = new Schema({ model: { type: String, required: true, index: { unique: true } }, idx: { type: Number, default: 0 } }); ModelIncrementSchema.statics.getNextId = async function(modelName, callback) { let incr = await this.findOne({ model: modelName }); if (!incr) incr = await new this({ model: modelName }).save(); incr.idx++; incr.save(); return incr.idx; }; const … Read more

body-parser – extended option (qs vs querystring)

The reason for this message is that body-parser is about to change default value for extended from true to false. Extended protocol uses qs library to parse x-www-form-urlencoded data. The main advantage of qs is that it uses very powerful serialization/deserialization algorithm, capable of serializing any json-like data structure. But web-browsers don’t normally use this … Read more

How random is crypto#randomBytes?

How random is crypto.randomBytes()? Usually, random enough for whatever purpose you need. crypto.randomBytes() generates cryptographically secure random data: crypto.randomBytes(size[, callback]) Generates cryptographically strong pseudo-random data. The size argument is a number indicating the number of bytes to generate. This means that the random data is secure enough to use for encryption purposes. In fact, the … Read more

socket.io private message

No tutorial needed. The Socket.IO FAQ is pretty straightforward on this one: socket.emit(‘news’, { hello: ‘world’ }); EDIT: Folks are linking to this question when asking about how to get that socket object later. There is no need to. When a new client connects, save a reference to that socket on whatever object you’re keeping … Read more

How to chain a variable number of promises in Q, in order?

There’s a nice clean way to to this with [].reduce. var chain = itemsToProcess.reduce(function (previous, item) { return previous.then(function (previousValue) { // do what you want with previous value // return your async operation return Q.delay(100); }) }, Q.resolve(/* set the first “previousValue” here */)); chain.then(function (lastResult) { // … }); reduce iterates through the … Read more