How to use bson

Comprehensive bson code examples:

How to use bson.BSON:

11
12
13
14
15
16
17
18
19
20
21
var fs = require("fs");
var pool = require('./public/pool.js');
var schlaunquer = require('./public/schlaunquer.js');
var adminB = require('./public/adminB.js');
var bson = require("bson");
var BSON = new bson.BSON();


//connect and check mongoDB
var db;
var dbURI = process.env.ATLAS_DB_KEY || 'mongodb://mongo:27017/schlaugh';

How to use bson.UUID:

48
49
50
51
52
53
54
55
56
.. code-block:: javascript

   const { UUID } = require('bson');
   ...
   const client = new MongoClient(uri, { 
     pkFactory: { createPk: () =>  new UUID().toBinary() }
   });

.. note:: Data Consistency

How to use bson.prototype:

28
29
30
31
32
33
34
35
36
37
38
/*!
 * Convenience `valueOf()` to allow comparing ObjectIds using double equals re: gh-7299
 */


if (!ObjectId.prototype.hasOwnProperty('valueOf')) {
  ObjectId.prototype.valueOf = function objectIdValueOf() {
    return this.toString();
  };
}

How to use bson.calculateObjectSize:

1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
const getObjSize = (obj) => {
	if (!obj) {
		return 0;
	}


	return BSON.calculateObjectSize(obj) / (1024 * 1024);
};


const filterDocuments = (rows) => {
	const size = getObjSize(rows);

How to use bson.BSONNative:

0
1
2
3
4
5
6
7
8
9
'use strict';

var assert = require('assert');
var bitcore = require('bitcore-lib');
var bson = require('bson');
var BSON = new bson.BSONNative.BSON();

var utils = require('../utils');

/**

How to use bson.Map:

52
53
54
55
56
57
58
59
60
61
/** @type {import('bson').Int32} */
module.exports.Int32 = BSONJS.Int32;
/** @type {import('bson').Long} */
module.exports.Long = BSONJS.Long;
/** @type {import('bson').Map} */
module.exports.Map = BSONJS.Map;
/** @type {import('bson').MaxKey} */
module.exports.MaxKey = BSONJS.MaxKey;
/** @type {import('bson').MinKey} */
module.exports.MinKey = BSONJS.MinKey;

How to use bson.ObjectID:

33
34
35
36
37
38
39
40
41
42
  message: "Refferal Amount",
};
db.get()
  .collection(collections.WALLET_COLLECTION)
  .updateOne(
    { userID: ObjectID(userId) },
    {
      $inc: {
        balance: parseInt(50),
      },

How to use bson.encode:

17
18
19
20
21
22
23
24
25
26
        
### encode
**以 bson 格式编码变量**

```JavaScript
static Buffer bson.encode(Object data);
```

调用参数:
* data: Object, 要编码的变量

How to use bson.BSONPure:

2
3
4
5
6
7
8
9
10
11
var fs = Promise.promisifyAll(require('fs'));
var bcrypt = require('bcrypt');
var hash = Promise.promisify(bcrypt.hash);
var compare = Promise.promisify(bcrypt.compare);
var bson = require('bson');
var BSON = bson.BSONPure.BSON;

var app = express();

var PASSWORD_FILE = './password.bson';

How to use bson.decode:

31
32
33
34
35
36
37
38
39
40
--------------------------
### decode
**以 bson 方式解码字符串为一个变量**

```JavaScript
static Object bson.decode(Buffer data);
```

调用参数:
* data: [Buffer](../../object/ifs/Buffer.md), 要解码的二进制数据

How to use bson.BSONSymbol:

62
63
64
65
66
67
68
69
70
71
72
/** @type {import('bson').ObjectId} */
module.exports.ObjectId = BSONJS.ObjectId;
/** @type {import('bson').BSONRegExp} */
module.exports.BSONRegExp = BSONJS.BSONRegExp;
/** @type {import('bson').BSONSymbol} */
module.exports.BSONSymbol = BSONJS.BSONSymbol;
/** @type {import('bson').Timestamp} */
module.exports.Timestamp = BSONJS.Timestamp;


// special case for deprecated names

How to use bson.serialize:

121
122
123
124
125
126
127
128
129
130
    logr.info('Index reconstructed up to block #'+blocks.height+' in '+(new Date().getTime()-startTime)+'ms')
},
appendBlock: (newBlock) => {
    assert(blocks.isOpen,blocks.notOpenError)
    assert(newBlock._id === blocks.height+1,'could not append non-next block')
    let serializedBlock = BSON.serialize(newBlock)
    let newBlockSize = BigInt(serializedBlock.length)
    fs.writeSync(blocks.fd,serializedBlock)
    blocks.appendIndex(blocks.bsonSize)
    blocks.bsonSize += newBlockSize

How to use bson.DBRef:

42
43
44
45
46
47
48
49
50
51
/** @type {import('bson').Binary} */
module.exports.Binary = BSONJS.Binary;
/** @type {import('bson').Code} */
module.exports.Code = BSONJS.Code;
/** @type {import('bson').DBRef} */
module.exports.DBRef = BSONJS.DBRef;
/** @type {import('bson').Decimal128} */
module.exports.Decimal128 = BSONJS.Decimal128;
/** @type {import('bson').Double} */
module.exports.Double = BSONJS.Double;

How to use bson.EJSON:

4
5
6
7
8
9
10
11
12
13
14
const bson = require('bson');
var debug = require('debug')('mongodb-query-parser:test');


function convert(string) {
  var res = parser.parseFilter(string);
  var ret = bson.EJSON.serialize(res, { legacy: true, relaxed: false });
  debug('converted', { input: string, parsed: res, encoded: ret });
  return ret;
}

How to use bson.MaxKey:

1
2
3
4
5
6
7
8
9
10
11


const expect = require('chai').expect;
const bson = require('bson');
const ObjectId = bson.ObjectId;
const MinKey = bson.MinKey;
const MaxKey = bson.MaxKey;
const Binary = bson.Binary;
const BSONRegExp = bson.BSONRegExp;
const Code = bson.Code;
const Timestamp = bson.Timestamp;

How to use bson.Binary:

2
3
4
5
6
7
8
9
10
11
const expect = require('chai').expect;
const bson = require('bson');
const ObjectId = bson.ObjectId;
const MinKey = bson.MinKey;
const MaxKey = bson.MaxKey;
const Binary = bson.Binary;
const BSONRegExp = bson.BSONRegExp;
const Code = bson.Code;
const Timestamp = bson.Timestamp;
const Long = bson.Long;

How to use bson.Double:

7
8
9
10
11
12
13
14
15
16
const Binary = bson.Binary;
const BSONRegExp = bson.BSONRegExp;
const Code = bson.Code;
const Timestamp = bson.Timestamp;
const Long = bson.Long;
const Double = bson.Double;
const Int32 = bson.Int32;
const Decimal128 = bson.Decimal128;
const TypeChecker = require('../');

How to use bson.Int32:

8
9
10
11
12
13
14
15
16
17
18
const BSONRegExp = bson.BSONRegExp;
const Code = bson.Code;
const Timestamp = bson.Timestamp;
const Long = bson.Long;
const Double = bson.Double;
const Int32 = bson.Int32;
const Decimal128 = bson.Decimal128;
const TypeChecker = require('../');


describe('TypeChecker', function() {

How to use bson.deserializeStream:

190
191
192
193
194
195
196
197
198
199
    let docSizeEnd = docSizeBufEnd.readInt32LE(0)
    let rangeSize = docPositionEnd-docPosition+docSizeEnd
    let docBuf = Buffer.alloc(rangeSize)
    let docArr = []
    fs.readSync(blocks.fd,docBuf,{offset: 0, position: docPosition, length: rangeSize})
    BSON.deserializeStream(docBuf,0,end-start+1,docArr,0)
    return docArr
},
fillInMemoryBlocks: (headBlock = blocks.height+1) => {
    assert(blocks.isOpen,blocks.notOpenError)

How to use bson.Decimal128:

36
37
38
39
40
41
42
43
44
45
},
NumberDecimal: function(s) {
  if (s === undefined) {
    s = '0';
  }
  return bson.Decimal128.fromString(s.toString());
},
NumberInt: function(s) {
  return parseInt(s, 10);
},

How to use bson.Timestamp:

5
6
7
8
9
10
11
12
13
14
const MinKey = bson.MinKey;
const MaxKey = bson.MaxKey;
const Binary = bson.Binary;
const BSONRegExp = bson.BSONRegExp;
const Code = bson.Code;
const Timestamp = bson.Timestamp;
const Long = bson.Long;
const Double = bson.Double;
const Int32 = bson.Int32;
const Decimal128 = bson.Decimal128;

How to use bson.BSONRegExp:

176
177
178
179
180
181
182
183
184
185
  );
  return bson.Long.fromBits(...rhs);
}

emitRegex(ctx, pattern, flags) {
  return new bson.BSONRegExp(pattern, flags);
}

emit_array(ctx) {
  ctx.type = this.Types._array;

How to use bson.deserialize:

155
156
157
158
159
160
161
162
163
164
    let docSizeBuf = Buffer.alloc(4)
    fs.readSync(blocks.fd,docSizeBuf,{offset: 0, position: docPosition, length: 4})
    let docSize = docSizeBuf.readInt32LE(0)
    let docBuf = Buffer.alloc(docSize)
    fs.readSync(blocks.fd,docBuf,{offset: 0, position: docPosition, length: docSize})
    return BSON.deserialize(docBuf)
},
readRange: (start,end) => {
    if (!blocks.isOpen)
        throw new Error(blocks.notOpenError)

How to use bson.MinKey:

28
29
30
31
32
33
34
35
36
37

```javascript
// Example schema with a field default set to MinKey
const mySchema = new Schema({
  name: String,
  priority: { type: Schema.Types.MinKey, default: new MinKey() },
});
```

- When you need to find a document with the minimum value for a specific field.

How to use bson.Code:

30
31
32
33
34
35
36
37
38
39
MinKey: bson.MinKey,
ObjectId: bson.ObjectId,
BSONSymbol: bson.BSONSymbol,
Timestamp: bson.Timestamp,
Code: function(c, s) {
  return new bson.Code(c, s);
},
NumberDecimal: function(s) {
  if (s === undefined) {
    s = '0';

How to use bson.Long:

172
173
174
175
176
177
178
179
180
181
  ctx.type = this.Types.Long;
  const symbolType = this.Symbols.Long.attr.fromBits;
  const rhs = this.checkArguments(
    symbolType.args, this.getArguments(ctx), 'Long.fromBits'
  );
  return bson.Long.fromBits(...rhs);
}

emitRegex(ctx, pattern, flags) {
  return new bson.BSONRegExp(pattern, flags);

How to use bson.ObjectId:

35
36
37
38
39
40
41
42
43
44
```js
import { BSON, EJSON, ObjectId } from 'bson';
// or:
// const { BSON, EJSON, ObjectId } = require('bson');

const bytes = BSON.serialize({ _id: new ObjectId() });
console.log(bytes);
const doc = BSON.deserialize(bytes);
console.log(EJSON.stringify(doc));
// {"_id":{"$oid":"..."}}