My API consumes JSON and saves it in a record. However, I would like to impose a size limit on the object. For example, in MongoDB the document size must be less than 16MB. How should I go about it in Node.js?
MongoDB uses BSON to store objects so the calculated size will need to depend on BSON. Take a look at https://www.npmjs.com/package/bson:
import bson from 'bson'
const BSON = new bson.BSONPure.BSON()
BSON.calculateObjectSize({foo: 'bar'}) // => 18 bytes
This value will be close but still approximate since Mongo uses further optimizations.
If you are about to exceed the MongoDB document size limit, you sould rethink your data structures.
Sibelius Seraphini
Full Stack Developer #reactnative #redux #relay #graphql #webpack #koa #react
I do this
npm i -S json-sizeand then somewhere in my code.import jsonSize from 'json-size' console.log(jsonSize({foo: 'bar'})) //=> 13This is what
json-sizeis all about. github.com/bendrucker/json-size/blob/master/index…'use strict' var bytes = require('utf8-length') module.exports = function jsonSize (value) { return bytes(JSON.stringify(value)) }json-sizehas a dependency ofutf8-lenghthwhich is nothing more than this. github.com/substack/utf8-length/blob/master/index…module.exports = function(s) { return ~-encodeURI(s).split(/%..|./).length }We can do it all by ourself now.
const bytes = (s) => { return ~-encodeURI(s).split(/%..|./).length } const jsonSize = (s) => { return bytes(JSON.stringify(s)) } console.log(jsonSize({foo: 'bar'})) //=> 13What's this tilde operator? joezimjs.com/javascript/great-mystery-of-the-tilde