Skip to content

Commit

Permalink
requested changes
Browse files Browse the repository at this point in the history
  • Loading branch information
aditi-khare-mongoDB committed Nov 8, 2024
1 parent 68f2ebd commit 021f84b
Show file tree
Hide file tree
Showing 23 changed files with 157 additions and 93 deletions.
1 change: 1 addition & 0 deletions docs/guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ The permitted SchemaTypes are:
* [Decimal128](api/mongoose.html#mongoose_Mongoose-Decimal128)
* [Map](schematypes.html#maps)
* [UUID](schematypes.html#uuid)
* [Int32](schematypes.html#int32)

Read more about [SchemaTypes here](schematypes.html).

Expand Down
17 changes: 17 additions & 0 deletions docs/schematypes.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ Check out [Mongoose's plugins search](http://plugins.mongoosejs.io) to find plug
* [Schema](#schemas)
* [UUID](#uuid)
* [BigInt](#bigint)
* [Int32](#int32)

### Example

Expand All @@ -68,6 +69,7 @@ const schema = new Schema({
mixed: Schema.Types.Mixed,
_someId: Schema.Types.ObjectId,
decimal: Schema.Types.Decimal128,
32bitInt: Schema.Types.Int32,
array: [],
ofString: [String],
ofNumber: [Number],
Expand Down Expand Up @@ -647,6 +649,21 @@ const question = new Question({ answer: 42n });
typeof question.answer; // 'bigint'
```

### Int32 {#int32}

Mongoose supports 32-bit integers as a SchemaType.
Int32s are stored as [32-bit integers in MongoDB (BSON type "int")](https://www.mongodb.com/docs/manual/reference/bson-types/).

```javascript
const studentsSchema = new Schema({
id: Int32
});
const Student = mongoose.model('Student', schema);

const student = new Student({ id: 1339 });
typeof student.id; // 'number'
```

## Getters {#getters}

Getters are like virtuals for paths defined in your schema. For example,
Expand Down
3 changes: 2 additions & 1 deletion docs/source/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ const files = [
'lib/types/subdocument.js',
'lib/types/arraySubdocument.js',
'lib/types/buffer.js',
'lib/types/.js',
'lib/types/decimal128.js',
'lib/types/int32.js',
'lib/types/map.js',
'lib/types/array/methods/index.js'
];
Expand Down
1 change: 1 addition & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ module.exports.Decimal128 = mongoose.Decimal128;
module.exports.Mixed = mongoose.Mixed;
module.exports.Date = mongoose.Date;
module.exports.Number = mongoose.Number;
module.exports.Int32 = mongoose.Int32;
module.exports.Error = mongoose.Error;
module.exports.MongooseError = mongoose.MongooseError;
module.exports.now = mongoose.now;
Expand Down
2 changes: 1 addition & 1 deletion lib/browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ exports.Schema = require('./schema');
* - [ObjectId](https://mongoosejs.com/docs/schematypes.html#objectids)
* - [Map](https://mongoosejs.com/docs/schematypes.html#maps)
* - [Subdocument](https://mongoosejs.com/docs/schematypes.html#schemas)
* - Int32
* - [Int32](https://mongoosejs.com/docs/schematypes.html#int32)
*
* Using this exposed access to the `ObjectId` type, we can construct ids on demand.
*
Expand Down
2 changes: 1 addition & 1 deletion lib/cast/int32.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ module.exports = function castInt32(val) {

const _val = Number(val);

if (!isNaN(_val) && _val === Math.round(_val) && _val > INT32_MIN && _val < INT32_MAX) {
if (_val !== _val | 0 && _val > INT32_MIN && _val < INT32_MAX) {
return _val;
}
assert.ok(false);
Expand Down
7 changes: 7 additions & 0 deletions lib/drivers/browser/int32.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/*!
* ignore
*/

'use strict';

module.exports = require('bson').Int32;

Check warning on line 7 in lib/drivers/browser/int32.js

View workflow job for this annotation

GitHub Actions / Lint JS-Files

Newline required at end of file but not found
8 changes: 4 additions & 4 deletions lib/mongoose.js
Original file line number Diff line number Diff line change
Expand Up @@ -987,7 +987,7 @@ Mongoose.prototype.VirtualType = VirtualType;
* - [ObjectId](https://mongoosejs.com/docs/schematypes.html#objectids)
* - [Map](https://mongoosejs.com/docs/schematypes.html#maps)
* - [Subdocument](https://mongoosejs.com/docs/schematypes.html#schemas)
* - Int32
* - [Int32](https://mongoosejs.com/docs/schematypes.html#int32)
*
* Using this exposed access to the `ObjectId` type, we can construct ids on demand.
*
Expand Down Expand Up @@ -1142,15 +1142,15 @@ Mongoose.prototype.Decimal128 = SchemaTypes.Decimal128;

/**
* The Mongoose Int32 [SchemaType](https://mongoosejs.com/docs/schematypes.html). Used for
* declaring paths in your schema that should be 32-bit integers floating points.
* declaring paths in your schema that should be 32-bit integers.
* Do not use this to create a new Int32 instance, use `mongoose.Types.Int32`
* instead.
*
* #### Example:
*
* const vehicleSchema = new Schema({ numberOfCows: mongoose.Int32 });
* const vehicleSchema = new Schema({ numTires: mongoose.Int32 });
*
* @property Decimal128
* @property Int32
* @api public
*/
Mongoose.prototype.Int32 = SchemaTypes.Int32;
Expand Down
1 change: 0 additions & 1 deletion lib/query.js
Original file line number Diff line number Diff line change
Expand Up @@ -1634,7 +1634,6 @@ Query.prototype.getOptions = function() {
* - [projection](https://mongoosejs.com/docs/api/query.html#Query.prototype.projection())
* - sanitizeProjection
* - useBigInt64
* - promoteValues
*
* The following options are only for all operations **except** `updateOne()`, `updateMany()`, `deleteOne()`, and `deleteMany()`:
*
Expand Down
2 changes: 2 additions & 0 deletions lib/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -1494,6 +1494,8 @@ Schema.prototype.interpretAsType = function(path, obj, options) {
name = 'ObjectId';
} else if (type === Types.Decimal128) {
name = 'Decimal128';
} else if (type === Types.Int32) {
name = 'Int32';
} else {
name = type == null ? '' + type : type.toString();
}
Expand Down
2 changes: 1 addition & 1 deletion lib/schema/bigint.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ SchemaBigInt.setters = [];
SchemaBigInt.get = SchemaType.get;

/**
* Get/set the function used to cast arbitrary values to booleans.
* Get/set the function used to cast arbitrary values to bigints.
*
* #### Example:
*
Expand Down
25 changes: 24 additions & 1 deletion lib/schema/int32.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ SchemaInt32._cast = castInt32;
/**
* Sets a default option for all Int32 instances.
*
* #### Example:
*
* // Make all Int32 fields required by default
* mongoose.Schema.Int32.set('required', true);
*
* @param {String} option The option you'd like to set the value for
* @param {Any} value value for option
Expand All @@ -63,6 +67,11 @@ SchemaInt32.setters = [];
/**
* Attaches a getter for all Int32 instances
*
* #### Example:
*
* // Converts int32 to be a represent milliseconds upon access
* mongoose.Schema.Int32.get(v => v == null ? '0 ms' : v.toString() + ' ms');
*
* @param {Function} getter
* @return {this}
* @function get
Expand All @@ -73,7 +82,21 @@ SchemaInt32.setters = [];
SchemaInt32.get = SchemaType.get;

/**
* Get/set the function used to cast arbitrary values to booleans.
* Get/set the function used to cast arbitrary values to 32-bit integers
*
* #### Example:
*
* // Make Mongoose cast NaN to 0
* const defaultCast = mongoose.Schema.Int32.cast();
* mongoose.Schema.Int32.cast(v => {
* if (isNaN(v)) {
* return 0;
* }
* return defaultCast(v);
* });
*
* // Or disable casting for Int32s entirely
* mongoose.Schema.Int32.cast(false);
*
* @param {Function} caster
* @return {Function}
Expand Down
1 change: 1 addition & 0 deletions lib/types/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ exports.Embedded = require('./arraySubdocument');
exports.DocumentArray = require('./documentArray');
exports.Decimal128 = require('./decimal128');
exports.ObjectId = require('./objectid');
exports.ObjectId = require('./int32');

exports.Map = require('./map');

Expand Down
13 changes: 13 additions & 0 deletions lib/types/int32.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/**
* Int32 type constructor
*
* #### Example:
*
* const id = new mongoose.Types.Int32('-2');
*
* @constructor Int32
*/

'use strict';

module.exports = require('bson').Int32;

Check warning on line 13 in lib/types/int32.js

View workflow job for this annotation

GitHub Actions / Lint JS-Files

Newline required at end of file but not found
4 changes: 4 additions & 0 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@ exports.deepEqual = function deepEqual(a, b) {
return a.toString() === b.toString();
}

if (isBsonType(a, 'Int32') && isBsonType(b, 'In32')) {
return a.value === b.value();
}

if (a instanceof RegExp && b instanceof RegExp) {
return a.source === b.source &&
a.ignoreCase === b.ignoreCase &&
Expand Down
5 changes: 5 additions & 0 deletions test/helpers/isBsonType.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const isBsonType = require('../../lib/helpers/isBsonType');

const Decimal128 = require('mongodb').Decimal128;
const ObjectId = require('mongodb').ObjectId;
const Int32 = require('mongodb').Int32;

describe('isBsonType', () => {
it('true for any object with _bsontype property equal typename', () => {
Expand All @@ -30,4 +31,8 @@ describe('isBsonType', () => {
it('true for ObjectId', () => {
assert.ok(isBsonType(new ObjectId(), 'ObjectId'));
});

it('true for Int32', () => {
assert.ok(isBsonType(new Int32(), 'Int32'));
});
});
37 changes: 0 additions & 37 deletions test/int32.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

const assert = require('assert');
const start = require('./common');
const BSONInt32 = require('bson').Int32;

const mongoose = start.mongoose;
const Schema = mongoose.Schema;
Expand Down Expand Up @@ -219,42 +218,6 @@ describe('Int32', function() {
});
});

describe('promoteValues', function() {
describe('when promoteValues is false', function() {
it('find returns BSON Int32', async function() {
await Test.create({ myInt: 7 });

const doc = await Test.findOne({ myInt: 7 })
.setOptions({ promoteValues: false });
assert.ok(doc);
assert.ok(doc.myInt instanceof BSONInt32);
assert.equal(doc.myInt.value, 7);
});
});

describe('when promoteValues is undefined', function() {
it('find returns a JS number', async function() {
await Test.create({ myInt: 7 });
const doc = await Test.findOne({ myInt: 7 })
.setOptions({ promoteValues: undefined });
assert.ok(doc);
assert.ok(doc);
assert.equal(doc.myInt, 7);
});
});

describe('when promoteValues is true', function() {
it('find returns a JS number', async function() {
await Test.create({ myInt: 7 });

const doc = await Test.findOne({ myInt: 7 })
.setOptions({ promoteValues: false });
assert.ok(doc);
assert.equal(doc.myInt, 7);
});
});
});

it('can query with comparison operators', async function() {
await Test.create([
{ myInt: 1 },
Expand Down
1 change: 1 addition & 0 deletions test/types/schemaTypeOptions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ function defaultOptions() {
expectType<Record<string, any>>(new Schema.Types.Buffer('none').defaultOptions);
expectType<Record<string, any>>(new Schema.Types.Date('none').defaultOptions);
expectType<Record<string, any>>(new Schema.Types.Decimal128('none').defaultOptions);
expectType<Record<string, any>>(new Schema.Types.Int32('none').defaultOptions);
expectType<Record<string, any>>(new Schema.Types.DocumentArray('none').defaultOptions);
expectType<Record<string, any>>(new Schema.Types.Map('none').defaultOptions);
expectType<Record<string, any>>(new Schema.Types.Mixed('none').defaultOptions);
Expand Down
31 changes: 17 additions & 14 deletions types/inferrawdoctype.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,18 +102,21 @@ declare module 'mongoose' {
PathValueType extends 'decimal128' | 'Decimal128' | typeof Schema.Types.Decimal128 ? Types.Decimal128 :
IfEquals<PathValueType, Schema.Types.Decimal128> extends true ? Types.Decimal128 :
IfEquals<PathValueType, Types.Decimal128> extends true ? Types.Decimal128 :
IfEquals<PathValueType, Schema.Types.BigInt> extends true ? bigint :
IfEquals<PathValueType, BigInt> extends true ? bigint :
PathValueType extends 'bigint' | 'BigInt' | typeof Schema.Types.BigInt | typeof BigInt ? bigint :
PathValueType extends 'uuid' | 'UUID' | typeof Schema.Types.UUID ? Buffer :
IfEquals<PathValueType, Schema.Types.UUID> extends true ? Buffer :
PathValueType extends MapConstructor | 'Map' ? Map<string, ResolveRawPathType<Options['of']>> :
IfEquals<PathValueType, typeof Schema.Types.Map> extends true ? Map<string, ResolveRawPathType<Options['of']>> :
PathValueType extends ArrayConstructor ? any[] :
PathValueType extends typeof Schema.Types.Mixed ? any:
IfEquals<PathValueType, ObjectConstructor> extends true ? any:
IfEquals<PathValueType, {}> extends true ? any:
PathValueType extends typeof SchemaType ? PathValueType['prototype'] :
PathValueType extends Record<string, any> ? ObtainDocumentType<PathValueType, any, { typeKey: TypeKey }> :
unknown;
PathValueType extends 'int32' | 'Int32' | typeof Schema.Types.Int32 ? Types.Int32 :
IfEquals<PathValueType, Schema.Types.Int32> extends true ? Types.Int32 :
IfEquals<PathValueType, Types.Int32> extends true ? Types.Int32 :
IfEquals<PathValueType, Schema.Types.BigInt> extends true ? bigint :
IfEquals<PathValueType, BigInt> extends true ? bigint :
PathValueType extends 'bigint' | 'BigInt' | typeof Schema.Types.BigInt | typeof BigInt ? bigint :
PathValueType extends 'uuid' | 'UUID' | typeof Schema.Types.UUID ? Buffer :
IfEquals<PathValueType, Schema.Types.UUID> extends true ? Buffer :
PathValueType extends MapConstructor | 'Map' ? Map<string, ResolveRawPathType<Options['of']>> :
IfEquals<PathValueType, typeof Schema.Types.Map> extends true ? Map<string, ResolveRawPathType<Options['of']>> :
PathValueType extends ArrayConstructor ? any[] :
PathValueType extends typeof Schema.Types.Mixed ? any:
IfEquals<PathValueType, ObjectConstructor> extends true ? any:
IfEquals<PathValueType, {}> extends true ? any:
PathValueType extends typeof SchemaType ? PathValueType['prototype'] :
PathValueType extends Record<string, any> ? ObtainDocumentType<PathValueType, any, { typeKey: TypeKey }> :
unknown;
}
Loading

0 comments on commit 021f84b

Please sign in to comment.