@kikiutils/mongoose 2.2.0 → 2.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/utils.cjs +24 -0
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.ts +16 -0
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.mjs +24 -1
- package/dist/utils.mjs.map +1 -1
- package/package.json +7 -7
- package/src/utils.ts +27 -0
package/dist/utils.cjs
CHANGED
|
@@ -13,6 +13,29 @@ const mongoose__default = /*#__PURE__*/_interopDefaultCompat(mongoose);
|
|
|
13
13
|
const mongooseAggregatePaginate__default = /*#__PURE__*/_interopDefaultCompat(mongooseAggregatePaginate);
|
|
14
14
|
const mongoosePaginate__default = /*#__PURE__*/_interopDefaultCompat(mongoosePaginate);
|
|
15
15
|
|
|
16
|
+
/**
|
|
17
|
+
* Asserts that a Mongoose update operation was successful by checking that it was acknowledged
|
|
18
|
+
* and that at least the expected number of documents were modified.
|
|
19
|
+
*
|
|
20
|
+
* This function is intended for use with `updateOne`, `updateMany`, or any update operation
|
|
21
|
+
* that returns a MongoDB `UpdateResult`.
|
|
22
|
+
*
|
|
23
|
+
* @template T - The shape of the document being updated.
|
|
24
|
+
* @param updatePromise - A promise returned from a Mongoose update operation.
|
|
25
|
+
* @param expectedModifiedCount - The minimum number of documents expected to be modified. Defaults to 1.
|
|
26
|
+
* @throws Will throw an error if:
|
|
27
|
+
* - The operation was not acknowledged by MongoDB,
|
|
28
|
+
* - Fewer documents were modified than expected.
|
|
29
|
+
*/
|
|
30
|
+
async function assertMongooseUpdateSuccess(updatePromise, expectedModifiedCount = 1) {
|
|
31
|
+
const updateResult = await updatePromise;
|
|
32
|
+
if (!updateResult.acknowledged)
|
|
33
|
+
throw new Error('Update was not acknowledged.');
|
|
34
|
+
if (updateResult.modifiedCount < expectedModifiedCount) {
|
|
35
|
+
// eslint-disable-next-line style/max-len
|
|
36
|
+
throw new Error(`Expected to modify at least ${expectedModifiedCount} document(s), but modified ${updateResult.modifiedCount}.`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
16
39
|
/**
|
|
17
40
|
* Builds and returns a Mongoose model with specified schema and options.
|
|
18
41
|
*
|
|
@@ -75,6 +98,7 @@ async function mongooseDocumentOrObjectIdToDocument(documentOrObjectId, model, s
|
|
|
75
98
|
return documentOrObjectId;
|
|
76
99
|
}
|
|
77
100
|
|
|
101
|
+
exports.assertMongooseUpdateSuccess = assertMongooseUpdateSuccess;
|
|
78
102
|
exports.buildMongooseModel = buildMongooseModel;
|
|
79
103
|
exports.mongooseDocumentOrObjectIdToDocument = mongooseDocumentOrObjectIdToDocument;
|
|
80
104
|
//# sourceMappingURL=utils.cjs.map
|
package/dist/utils.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.cjs","sources":["../src/utils.ts"],"sourcesContent":["import mongoose, { Types } from 'mongoose';\nimport mongooseAggregatePaginate from 'mongoose-aggregate-paginate-v2';\nimport mongoosePaginate from 'mongoose-paginate-v2';\n\nimport { customMongooseOptions } from './_internals';\nimport { mongooseConnections } from './constants';\nimport type { setCustomMongooseOptions } from './options';\nimport mongooseNormalizePlugin from './plugins/normalize';\nimport type { BuildMongooseModelOptions } from './types/options';\n\nexport type DoNotRemoveOrUseThisType = typeof setCustomMongooseOptions;\n\n/**\n * Builds and returns a Mongoose model with specified schema and options.\n *\n * This function sets up a Mongoose model with optional plugins and timestamp settings.\n * It can optionally use a specified connection or the default connection.\n *\n * Determine the connection to use:\n * 1. Use the connection provided in the options, if available.\n * 2. Otherwise, use the default connection stored in `mongooseConnections`.\n * 3. If there's no default connection, create one using the MongoDB URI from the environment variables,\n * or fallback to a local MongoDB instance.\n *\n * You can set a function to be executed before the final build by using {@link setCustomMongooseOptions}.\n * However, ensure that this option is configured before calling {@link buildMongooseModel}.\n *\n * @template DocType - The type of the document.\n * @template Model - The type of the model, which extends `BaseMongoosePaginateModel`.\n * @template InstanceMethodsAndOverrides - The type for instance methods and overrides.\n * @template QueryHelpers - The type for additional query helpers.\n *\n * @param collection - The name of the collection.\n * @param name - The name of the model.\n * @param schema - The Mongoose schema to use for the model.\n * @param options - Optional settings for building the model.\n *\n * @returns The created Mongoose model.\n */\nexport function buildMongooseModel<\n DocType,\n Model extends BaseMongoosePaginateModel<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n InstanceMethodsAndOverrides = object,\n QueryHelpers = object,\n>(\n collection: string,\n name: string,\n schema: mongoose.Schema<DocType, Model, InstanceMethodsAndOverrides, QueryHelpers>,\n options?: BuildMongooseModelOptions,\n) {\n if (options?.enableNormalizePlugin !== false) schema.plugin(mongooseNormalizePlugin);\n schema.plugin(mongooseAggregatePaginate);\n schema.plugin(mongoosePaginate);\n schema.set('timestamps', options?.timestamps ?? schema.get('timestamps') ?? true);\n customMongooseOptions.beforeModelBuild?.(schema);\n // eslint-disable-next-line style/max-len\n const connection = options?.connection || (mongooseConnections.default ||= mongoose.createConnection(process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017'));\n return connection.model<DocType, Model, QueryHelpers>(name, schema, collection);\n}\n\n/**\n * Converts a document or ObjectId to a document using the specified model.\n *\n * This function takes a document or ObjectId and returns the corresponding document\n * from the database using the specified model. Optionally, specific fields can be selected.\n *\n * @template D - The type of the hydrated document.\n * @template DocType - The type of the document.\n * @template InstanceMethodsAndOverrides - The type for instance methods and overrides.\n * @template QueryHelpers - The type for additional query helpers.\n *\n * @param documentOrObjectId - The document or ObjectId to convert.\n * @param model - The Mongoose model to use for the conversion.\n * @param selectFields - Optional fields to select from the document.\n *\n * @returns The corresponding document or null if not found.\n */\nexport async function mongooseDocumentOrObjectIdToDocument<\n D extends MongooseHydratedDocument<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n DocType,\n InstanceMethodsAndOverrides,\n QueryHelpers,\n>(\n documentOrObjectId: MongooseDocumentOrObjectId<D>,\n model: BaseMongoosePaginateModel<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n selectFields?: string[],\n): Promise<D | null> {\n if (typeof documentOrObjectId === 'string' || documentOrObjectId instanceof Types.ObjectId) {\n return (await model.findById(documentOrObjectId).select(selectFields || [])) as D | null;\n }\n\n return documentOrObjectId;\n}\n"],"names":["mongooseNormalizePlugin","mongooseAggregatePaginate","mongoosePaginate","customMongooseOptions","mongooseConnections","mongoose","Types"],"mappings":";;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"utils.cjs","sources":["../src/utils.ts"],"sourcesContent":["import type { mongo } from 'mongoose';\nimport mongoose, { Types } from 'mongoose';\nimport mongooseAggregatePaginate from 'mongoose-aggregate-paginate-v2';\nimport mongoosePaginate from 'mongoose-paginate-v2';\n\nimport { customMongooseOptions } from './_internals';\nimport { mongooseConnections } from './constants';\nimport type { setCustomMongooseOptions } from './options';\nimport mongooseNormalizePlugin from './plugins/normalize';\nimport type { BuildMongooseModelOptions } from './types/options';\n\nexport type DoNotRemoveOrUseThisType = typeof setCustomMongooseOptions;\n\n/**\n * Asserts that a Mongoose update operation was successful by checking that it was acknowledged\n * and that at least the expected number of documents were modified.\n *\n * This function is intended for use with `updateOne`, `updateMany`, or any update operation\n * that returns a MongoDB `UpdateResult`.\n *\n * @template T - The shape of the document being updated.\n * @param updatePromise - A promise returned from a Mongoose update operation.\n * @param expectedModifiedCount - The minimum number of documents expected to be modified. Defaults to 1.\n * @throws Will throw an error if:\n * - The operation was not acknowledged by MongoDB,\n * - Fewer documents were modified than expected.\n */\nexport async function assertMongooseUpdateSuccess<T extends mongo.BSON.Document>(\n updatePromise: Promise<mongo.UpdateResult<T>>,\n expectedModifiedCount = 1,\n) {\n const updateResult = await updatePromise;\n if (!updateResult.acknowledged) throw new Error('Update was not acknowledged.');\n if (updateResult.modifiedCount < expectedModifiedCount) {\n // eslint-disable-next-line style/max-len\n throw new Error(`Expected to modify at least ${expectedModifiedCount} document(s), but modified ${updateResult.modifiedCount}.`);\n }\n}\n\n/**\n * Builds and returns a Mongoose model with specified schema and options.\n *\n * This function sets up a Mongoose model with optional plugins and timestamp settings.\n * It can optionally use a specified connection or the default connection.\n *\n * Determine the connection to use:\n * 1. Use the connection provided in the options, if available.\n * 2. Otherwise, use the default connection stored in `mongooseConnections`.\n * 3. If there's no default connection, create one using the MongoDB URI from the environment variables,\n * or fallback to a local MongoDB instance.\n *\n * You can set a function to be executed before the final build by using {@link setCustomMongooseOptions}.\n * However, ensure that this option is configured before calling {@link buildMongooseModel}.\n *\n * @template DocType - The type of the document.\n * @template Model - The type of the model, which extends `BaseMongoosePaginateModel`.\n * @template InstanceMethodsAndOverrides - The type for instance methods and overrides.\n * @template QueryHelpers - The type for additional query helpers.\n *\n * @param collection - The name of the collection.\n * @param name - The name of the model.\n * @param schema - The Mongoose schema to use for the model.\n * @param options - Optional settings for building the model.\n *\n * @returns The created Mongoose model.\n */\nexport function buildMongooseModel<\n DocType,\n Model extends BaseMongoosePaginateModel<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n InstanceMethodsAndOverrides = object,\n QueryHelpers = object,\n>(\n collection: string,\n name: string,\n schema: mongoose.Schema<DocType, Model, InstanceMethodsAndOverrides, QueryHelpers>,\n options?: BuildMongooseModelOptions,\n) {\n if (options?.enableNormalizePlugin !== false) schema.plugin(mongooseNormalizePlugin);\n schema.plugin(mongooseAggregatePaginate);\n schema.plugin(mongoosePaginate);\n schema.set('timestamps', options?.timestamps ?? schema.get('timestamps') ?? true);\n customMongooseOptions.beforeModelBuild?.(schema);\n // eslint-disable-next-line style/max-len\n const connection = options?.connection || (mongooseConnections.default ||= mongoose.createConnection(process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017'));\n return connection.model<DocType, Model, QueryHelpers>(name, schema, collection);\n}\n\n/**\n * Converts a document or ObjectId to a document using the specified model.\n *\n * This function takes a document or ObjectId and returns the corresponding document\n * from the database using the specified model. Optionally, specific fields can be selected.\n *\n * @template D - The type of the hydrated document.\n * @template DocType - The type of the document.\n * @template InstanceMethodsAndOverrides - The type for instance methods and overrides.\n * @template QueryHelpers - The type for additional query helpers.\n *\n * @param documentOrObjectId - The document or ObjectId to convert.\n * @param model - The Mongoose model to use for the conversion.\n * @param selectFields - Optional fields to select from the document.\n *\n * @returns The corresponding document or null if not found.\n */\nexport async function mongooseDocumentOrObjectIdToDocument<\n D extends MongooseHydratedDocument<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n DocType,\n InstanceMethodsAndOverrides,\n QueryHelpers,\n>(\n documentOrObjectId: MongooseDocumentOrObjectId<D>,\n model: BaseMongoosePaginateModel<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n selectFields?: string[],\n): Promise<D | null> {\n if (typeof documentOrObjectId === 'string' || documentOrObjectId instanceof Types.ObjectId) {\n return (await model.findById(documentOrObjectId).select(selectFields || [])) as D | null;\n }\n\n return documentOrObjectId;\n}\n"],"names":["mongooseNormalizePlugin","mongooseAggregatePaginate","mongoosePaginate","customMongooseOptions","mongooseConnections","mongoose","Types"],"mappings":";;;;;;;;;;;;;;;AAaA;;;;;;;;;;;;;AAaG;AACI,eAAe,2BAA2B,CAC7C,aAA6C,EAC7C,qBAAqB,GAAG,CAAC,EAAA;AAEzB,IAAA,MAAM,YAAY,GAAG,MAAM,aAAa;IACxC,IAAI,CAAC,YAAY,CAAC,YAAY;AAAE,QAAA,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC;AAC/E,IAAA,IAAI,YAAY,CAAC,aAAa,GAAG,qBAAqB,EAAE;;QAEpD,MAAM,IAAI,KAAK,CAAC,CAA+B,4BAAA,EAAA,qBAAqB,CAA8B,2BAAA,EAAA,YAAY,CAAC,aAAa,CAAG,CAAA,CAAA,CAAC;;AAExI;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BG;AACG,SAAU,kBAAkB,CAM9B,UAAkB,EAClB,IAAY,EACZ,MAAkF,EAClF,OAAmC,EAAA;AAEnC,IAAA,IAAI,OAAO,EAAE,qBAAqB,KAAK,KAAK;AAAE,QAAA,MAAM,CAAC,MAAM,CAACA,iCAAuB,CAAC;AACpF,IAAA,MAAM,CAAC,MAAM,CAACC,kCAAyB,CAAC;AACxC,IAAA,MAAM,CAAC,MAAM,CAACC,yBAAgB,CAAC;AAC/B,IAAA,MAAM,CAAC,GAAG,CAAC,YAAY,EAAE,OAAO,EAAE,UAAU,IAAI,MAAM,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,IAAI,CAAC;AACjF,IAAAC,gCAAqB,CAAC,gBAAgB,GAAG,MAAM,CAAC;;IAEhD,MAAM,UAAU,GAAG,OAAO,EAAE,UAAU,KAAKC,6BAAmB,CAAC,OAAO,KAAKC,iBAAQ,CAAC,gBAAgB,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,IAAI,2BAA2B,CAAC,CAAC;IAC7J,OAAO,UAAU,CAAC,KAAK,CAA+B,IAAI,EAAE,MAAM,EAAE,UAAU,CAAC;AACnF;AAEA;;;;;;;;;;;;;;;;AAgBG;AACI,eAAe,oCAAoC,CAMtD,kBAAiD,EACjD,KAAoF,EACpF,YAAuB,EAAA;IAEvB,IAAI,OAAO,kBAAkB,KAAK,QAAQ,IAAI,kBAAkB,YAAYC,cAAK,CAAC,QAAQ,EAAE;AACxF,QAAA,QAAQ,MAAM,KAAK,CAAC,QAAQ,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,YAAY,IAAI,EAAE,CAAC;;AAG/E,IAAA,OAAO,kBAAkB;AAC7B;;;;;;"}
|
package/dist/utils.d.ts
CHANGED
|
@@ -1,7 +1,23 @@
|
|
|
1
|
+
import type { mongo } from 'mongoose';
|
|
1
2
|
import mongoose from 'mongoose';
|
|
2
3
|
import type { setCustomMongooseOptions } from './options';
|
|
3
4
|
import type { BuildMongooseModelOptions } from './types/options';
|
|
4
5
|
export type DoNotRemoveOrUseThisType = typeof setCustomMongooseOptions;
|
|
6
|
+
/**
|
|
7
|
+
* Asserts that a Mongoose update operation was successful by checking that it was acknowledged
|
|
8
|
+
* and that at least the expected number of documents were modified.
|
|
9
|
+
*
|
|
10
|
+
* This function is intended for use with `updateOne`, `updateMany`, or any update operation
|
|
11
|
+
* that returns a MongoDB `UpdateResult`.
|
|
12
|
+
*
|
|
13
|
+
* @template T - The shape of the document being updated.
|
|
14
|
+
* @param updatePromise - A promise returned from a Mongoose update operation.
|
|
15
|
+
* @param expectedModifiedCount - The minimum number of documents expected to be modified. Defaults to 1.
|
|
16
|
+
* @throws Will throw an error if:
|
|
17
|
+
* - The operation was not acknowledged by MongoDB,
|
|
18
|
+
* - Fewer documents were modified than expected.
|
|
19
|
+
*/
|
|
20
|
+
export declare function assertMongooseUpdateSuccess<T extends mongo.BSON.Document>(updatePromise: Promise<mongo.UpdateResult<T>>, expectedModifiedCount?: number): Promise<void>;
|
|
5
21
|
/**
|
|
6
22
|
* Builds and returns a Mongoose model with specified schema and options.
|
|
7
23
|
*
|
package/dist/utils.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,QAAmB,MAAM,UAAU,CAAC;AAM3C,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,WAAW,CAAC;AAE1D,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,iBAAiB,CAAC;AAEjE,MAAM,MAAM,wBAAwB,GAAG,OAAO,wBAAwB,CAAC;AAEvE;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,kBAAkB,CAC9B,OAAO,EACP,KAAK,SAAS,yBAAyB,CAAC,OAAO,EAAE,2BAA2B,EAAE,YAAY,CAAC,EAC3F,2BAA2B,GAAG,MAAM,EACpC,YAAY,GAAG,MAAM,EAErB,UAAU,EAAE,MAAM,EAClB,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,OAAO,EAAE,KAAK,EAAE,2BAA2B,EAAE,YAAY,CAAC,EAClF,OAAO,CAAC,EAAE,yBAAyB,SAUtC;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,oCAAoC,CACtD,CAAC,SAAS,wBAAwB,CAAC,OAAO,EAAE,2BAA2B,EAAE,YAAY,CAAC,EACtF,OAAO,EACP,2BAA2B,EAC3B,YAAY,EAEZ,kBAAkB,EAAE,0BAA0B,CAAC,CAAC,CAAC,EACjD,KAAK,EAAE,yBAAyB,CAAC,OAAO,EAAE,2BAA2B,EAAE,YAAY,CAAC,EACpF,YAAY,CAAC,EAAE,MAAM,EAAE,GACxB,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC,CAMnB"}
|
|
1
|
+
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,UAAU,CAAC;AACtC,OAAO,QAAmB,MAAM,UAAU,CAAC;AAM3C,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,WAAW,CAAC;AAE1D,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,iBAAiB,CAAC;AAEjE,MAAM,MAAM,wBAAwB,GAAG,OAAO,wBAAwB,CAAC;AAEvE;;;;;;;;;;;;;GAaG;AACH,wBAAsB,2BAA2B,CAAC,CAAC,SAAS,KAAK,CAAC,IAAI,CAAC,QAAQ,EAC3E,aAAa,EAAE,OAAO,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,EAC7C,qBAAqB,SAAI,iBAQ5B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,kBAAkB,CAC9B,OAAO,EACP,KAAK,SAAS,yBAAyB,CAAC,OAAO,EAAE,2BAA2B,EAAE,YAAY,CAAC,EAC3F,2BAA2B,GAAG,MAAM,EACpC,YAAY,GAAG,MAAM,EAErB,UAAU,EAAE,MAAM,EAClB,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,OAAO,EAAE,KAAK,EAAE,2BAA2B,EAAE,YAAY,CAAC,EAClF,OAAO,CAAC,EAAE,yBAAyB,SAUtC;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,oCAAoC,CACtD,CAAC,SAAS,wBAAwB,CAAC,OAAO,EAAE,2BAA2B,EAAE,YAAY,CAAC,EACtF,OAAO,EACP,2BAA2B,EAC3B,YAAY,EAEZ,kBAAkB,EAAE,0BAA0B,CAAC,CAAC,CAAC,EACjD,KAAK,EAAE,yBAAyB,CAAC,OAAO,EAAE,2BAA2B,EAAE,YAAY,CAAC,EACpF,YAAY,CAAC,EAAE,MAAM,EAAE,GACxB,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC,CAMnB"}
|
package/dist/utils.mjs
CHANGED
|
@@ -5,6 +5,29 @@ import { customMongooseOptions } from './_internals.mjs';
|
|
|
5
5
|
import { mongooseConnections } from './constants.mjs';
|
|
6
6
|
import { mongooseNormalizePlugin } from './plugins/normalize.mjs';
|
|
7
7
|
|
|
8
|
+
/**
|
|
9
|
+
* Asserts that a Mongoose update operation was successful by checking that it was acknowledged
|
|
10
|
+
* and that at least the expected number of documents were modified.
|
|
11
|
+
*
|
|
12
|
+
* This function is intended for use with `updateOne`, `updateMany`, or any update operation
|
|
13
|
+
* that returns a MongoDB `UpdateResult`.
|
|
14
|
+
*
|
|
15
|
+
* @template T - The shape of the document being updated.
|
|
16
|
+
* @param updatePromise - A promise returned from a Mongoose update operation.
|
|
17
|
+
* @param expectedModifiedCount - The minimum number of documents expected to be modified. Defaults to 1.
|
|
18
|
+
* @throws Will throw an error if:
|
|
19
|
+
* - The operation was not acknowledged by MongoDB,
|
|
20
|
+
* - Fewer documents were modified than expected.
|
|
21
|
+
*/
|
|
22
|
+
async function assertMongooseUpdateSuccess(updatePromise, expectedModifiedCount = 1) {
|
|
23
|
+
const updateResult = await updatePromise;
|
|
24
|
+
if (!updateResult.acknowledged)
|
|
25
|
+
throw new Error('Update was not acknowledged.');
|
|
26
|
+
if (updateResult.modifiedCount < expectedModifiedCount) {
|
|
27
|
+
// eslint-disable-next-line style/max-len
|
|
28
|
+
throw new Error(`Expected to modify at least ${expectedModifiedCount} document(s), but modified ${updateResult.modifiedCount}.`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
8
31
|
/**
|
|
9
32
|
* Builds and returns a Mongoose model with specified schema and options.
|
|
10
33
|
*
|
|
@@ -67,5 +90,5 @@ async function mongooseDocumentOrObjectIdToDocument(documentOrObjectId, model, s
|
|
|
67
90
|
return documentOrObjectId;
|
|
68
91
|
}
|
|
69
92
|
|
|
70
|
-
export { buildMongooseModel, mongooseDocumentOrObjectIdToDocument };
|
|
93
|
+
export { assertMongooseUpdateSuccess, buildMongooseModel, mongooseDocumentOrObjectIdToDocument };
|
|
71
94
|
//# sourceMappingURL=utils.mjs.map
|
package/dist/utils.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.mjs","sources":["../src/utils.ts"],"sourcesContent":["import mongoose, { Types } from 'mongoose';\nimport mongooseAggregatePaginate from 'mongoose-aggregate-paginate-v2';\nimport mongoosePaginate from 'mongoose-paginate-v2';\n\nimport { customMongooseOptions } from './_internals';\nimport { mongooseConnections } from './constants';\nimport type { setCustomMongooseOptions } from './options';\nimport mongooseNormalizePlugin from './plugins/normalize';\nimport type { BuildMongooseModelOptions } from './types/options';\n\nexport type DoNotRemoveOrUseThisType = typeof setCustomMongooseOptions;\n\n/**\n * Builds and returns a Mongoose model with specified schema and options.\n *\n * This function sets up a Mongoose model with optional plugins and timestamp settings.\n * It can optionally use a specified connection or the default connection.\n *\n * Determine the connection to use:\n * 1. Use the connection provided in the options, if available.\n * 2. Otherwise, use the default connection stored in `mongooseConnections`.\n * 3. If there's no default connection, create one using the MongoDB URI from the environment variables,\n * or fallback to a local MongoDB instance.\n *\n * You can set a function to be executed before the final build by using {@link setCustomMongooseOptions}.\n * However, ensure that this option is configured before calling {@link buildMongooseModel}.\n *\n * @template DocType - The type of the document.\n * @template Model - The type of the model, which extends `BaseMongoosePaginateModel`.\n * @template InstanceMethodsAndOverrides - The type for instance methods and overrides.\n * @template QueryHelpers - The type for additional query helpers.\n *\n * @param collection - The name of the collection.\n * @param name - The name of the model.\n * @param schema - The Mongoose schema to use for the model.\n * @param options - Optional settings for building the model.\n *\n * @returns The created Mongoose model.\n */\nexport function buildMongooseModel<\n DocType,\n Model extends BaseMongoosePaginateModel<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n InstanceMethodsAndOverrides = object,\n QueryHelpers = object,\n>(\n collection: string,\n name: string,\n schema: mongoose.Schema<DocType, Model, InstanceMethodsAndOverrides, QueryHelpers>,\n options?: BuildMongooseModelOptions,\n) {\n if (options?.enableNormalizePlugin !== false) schema.plugin(mongooseNormalizePlugin);\n schema.plugin(mongooseAggregatePaginate);\n schema.plugin(mongoosePaginate);\n schema.set('timestamps', options?.timestamps ?? schema.get('timestamps') ?? true);\n customMongooseOptions.beforeModelBuild?.(schema);\n // eslint-disable-next-line style/max-len\n const connection = options?.connection || (mongooseConnections.default ||= mongoose.createConnection(process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017'));\n return connection.model<DocType, Model, QueryHelpers>(name, schema, collection);\n}\n\n/**\n * Converts a document or ObjectId to a document using the specified model.\n *\n * This function takes a document or ObjectId and returns the corresponding document\n * from the database using the specified model. Optionally, specific fields can be selected.\n *\n * @template D - The type of the hydrated document.\n * @template DocType - The type of the document.\n * @template InstanceMethodsAndOverrides - The type for instance methods and overrides.\n * @template QueryHelpers - The type for additional query helpers.\n *\n * @param documentOrObjectId - The document or ObjectId to convert.\n * @param model - The Mongoose model to use for the conversion.\n * @param selectFields - Optional fields to select from the document.\n *\n * @returns The corresponding document or null if not found.\n */\nexport async function mongooseDocumentOrObjectIdToDocument<\n D extends MongooseHydratedDocument<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n DocType,\n InstanceMethodsAndOverrides,\n QueryHelpers,\n>(\n documentOrObjectId: MongooseDocumentOrObjectId<D>,\n model: BaseMongoosePaginateModel<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n selectFields?: string[],\n): Promise<D | null> {\n if (typeof documentOrObjectId === 'string' || documentOrObjectId instanceof Types.ObjectId) {\n return (await model.findById(documentOrObjectId).select(selectFields || [])) as D | null;\n }\n\n return documentOrObjectId;\n}\n"],"names":[],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"utils.mjs","sources":["../src/utils.ts"],"sourcesContent":["import type { mongo } from 'mongoose';\nimport mongoose, { Types } from 'mongoose';\nimport mongooseAggregatePaginate from 'mongoose-aggregate-paginate-v2';\nimport mongoosePaginate from 'mongoose-paginate-v2';\n\nimport { customMongooseOptions } from './_internals';\nimport { mongooseConnections } from './constants';\nimport type { setCustomMongooseOptions } from './options';\nimport mongooseNormalizePlugin from './plugins/normalize';\nimport type { BuildMongooseModelOptions } from './types/options';\n\nexport type DoNotRemoveOrUseThisType = typeof setCustomMongooseOptions;\n\n/**\n * Asserts that a Mongoose update operation was successful by checking that it was acknowledged\n * and that at least the expected number of documents were modified.\n *\n * This function is intended for use with `updateOne`, `updateMany`, or any update operation\n * that returns a MongoDB `UpdateResult`.\n *\n * @template T - The shape of the document being updated.\n * @param updatePromise - A promise returned from a Mongoose update operation.\n * @param expectedModifiedCount - The minimum number of documents expected to be modified. Defaults to 1.\n * @throws Will throw an error if:\n * - The operation was not acknowledged by MongoDB,\n * - Fewer documents were modified than expected.\n */\nexport async function assertMongooseUpdateSuccess<T extends mongo.BSON.Document>(\n updatePromise: Promise<mongo.UpdateResult<T>>,\n expectedModifiedCount = 1,\n) {\n const updateResult = await updatePromise;\n if (!updateResult.acknowledged) throw new Error('Update was not acknowledged.');\n if (updateResult.modifiedCount < expectedModifiedCount) {\n // eslint-disable-next-line style/max-len\n throw new Error(`Expected to modify at least ${expectedModifiedCount} document(s), but modified ${updateResult.modifiedCount}.`);\n }\n}\n\n/**\n * Builds and returns a Mongoose model with specified schema and options.\n *\n * This function sets up a Mongoose model with optional plugins and timestamp settings.\n * It can optionally use a specified connection or the default connection.\n *\n * Determine the connection to use:\n * 1. Use the connection provided in the options, if available.\n * 2. Otherwise, use the default connection stored in `mongooseConnections`.\n * 3. If there's no default connection, create one using the MongoDB URI from the environment variables,\n * or fallback to a local MongoDB instance.\n *\n * You can set a function to be executed before the final build by using {@link setCustomMongooseOptions}.\n * However, ensure that this option is configured before calling {@link buildMongooseModel}.\n *\n * @template DocType - The type of the document.\n * @template Model - The type of the model, which extends `BaseMongoosePaginateModel`.\n * @template InstanceMethodsAndOverrides - The type for instance methods and overrides.\n * @template QueryHelpers - The type for additional query helpers.\n *\n * @param collection - The name of the collection.\n * @param name - The name of the model.\n * @param schema - The Mongoose schema to use for the model.\n * @param options - Optional settings for building the model.\n *\n * @returns The created Mongoose model.\n */\nexport function buildMongooseModel<\n DocType,\n Model extends BaseMongoosePaginateModel<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n InstanceMethodsAndOverrides = object,\n QueryHelpers = object,\n>(\n collection: string,\n name: string,\n schema: mongoose.Schema<DocType, Model, InstanceMethodsAndOverrides, QueryHelpers>,\n options?: BuildMongooseModelOptions,\n) {\n if (options?.enableNormalizePlugin !== false) schema.plugin(mongooseNormalizePlugin);\n schema.plugin(mongooseAggregatePaginate);\n schema.plugin(mongoosePaginate);\n schema.set('timestamps', options?.timestamps ?? schema.get('timestamps') ?? true);\n customMongooseOptions.beforeModelBuild?.(schema);\n // eslint-disable-next-line style/max-len\n const connection = options?.connection || (mongooseConnections.default ||= mongoose.createConnection(process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017'));\n return connection.model<DocType, Model, QueryHelpers>(name, schema, collection);\n}\n\n/**\n * Converts a document or ObjectId to a document using the specified model.\n *\n * This function takes a document or ObjectId and returns the corresponding document\n * from the database using the specified model. Optionally, specific fields can be selected.\n *\n * @template D - The type of the hydrated document.\n * @template DocType - The type of the document.\n * @template InstanceMethodsAndOverrides - The type for instance methods and overrides.\n * @template QueryHelpers - The type for additional query helpers.\n *\n * @param documentOrObjectId - The document or ObjectId to convert.\n * @param model - The Mongoose model to use for the conversion.\n * @param selectFields - Optional fields to select from the document.\n *\n * @returns The corresponding document or null if not found.\n */\nexport async function mongooseDocumentOrObjectIdToDocument<\n D extends MongooseHydratedDocument<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n DocType,\n InstanceMethodsAndOverrides,\n QueryHelpers,\n>(\n documentOrObjectId: MongooseDocumentOrObjectId<D>,\n model: BaseMongoosePaginateModel<DocType, InstanceMethodsAndOverrides, QueryHelpers>,\n selectFields?: string[],\n): Promise<D | null> {\n if (typeof documentOrObjectId === 'string' || documentOrObjectId instanceof Types.ObjectId) {\n return (await model.findById(documentOrObjectId).select(selectFields || [])) as D | null;\n }\n\n return documentOrObjectId;\n}\n"],"names":[],"mappings":";;;;;;;AAaA;;;;;;;;;;;;;AAaG;AACI,eAAe,2BAA2B,CAC7C,aAA6C,EAC7C,qBAAqB,GAAG,CAAC,EAAA;AAEzB,IAAA,MAAM,YAAY,GAAG,MAAM,aAAa;IACxC,IAAI,CAAC,YAAY,CAAC,YAAY;AAAE,QAAA,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC;AAC/E,IAAA,IAAI,YAAY,CAAC,aAAa,GAAG,qBAAqB,EAAE;;QAEpD,MAAM,IAAI,KAAK,CAAC,CAA+B,4BAAA,EAAA,qBAAqB,CAA8B,2BAAA,EAAA,YAAY,CAAC,aAAa,CAAG,CAAA,CAAA,CAAC;;AAExI;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BG;AACG,SAAU,kBAAkB,CAM9B,UAAkB,EAClB,IAAY,EACZ,MAAkF,EAClF,OAAmC,EAAA;AAEnC,IAAA,IAAI,OAAO,EAAE,qBAAqB,KAAK,KAAK;AAAE,QAAA,MAAM,CAAC,MAAM,CAAC,uBAAuB,CAAC;AACpF,IAAA,MAAM,CAAC,MAAM,CAAC,yBAAyB,CAAC;AACxC,IAAA,MAAM,CAAC,MAAM,CAAC,gBAAgB,CAAC;AAC/B,IAAA,MAAM,CAAC,GAAG,CAAC,YAAY,EAAE,OAAO,EAAE,UAAU,IAAI,MAAM,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,IAAI,CAAC;AACjF,IAAA,qBAAqB,CAAC,gBAAgB,GAAG,MAAM,CAAC;;IAEhD,MAAM,UAAU,GAAG,OAAO,EAAE,UAAU,KAAK,mBAAmB,CAAC,OAAO,KAAK,QAAQ,CAAC,gBAAgB,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,IAAI,2BAA2B,CAAC,CAAC;IAC7J,OAAO,UAAU,CAAC,KAAK,CAA+B,IAAI,EAAE,MAAM,EAAE,UAAU,CAAC;AACnF;AAEA;;;;;;;;;;;;;;;;AAgBG;AACI,eAAe,oCAAoC,CAMtD,kBAAiD,EACjD,KAAoF,EACpF,YAAuB,EAAA;IAEvB,IAAI,OAAO,kBAAkB,KAAK,QAAQ,IAAI,kBAAkB,YAAY,KAAK,CAAC,QAAQ,EAAE;AACxF,QAAA,QAAQ,MAAM,KAAK,CAAC,QAAQ,CAAC,kBAAkB,CAAC,CAAC,MAAM,CAAC,YAAY,IAAI,EAAE,CAAC;;AAG/E,IAAA,OAAO,kBAAkB;AAC7B;;;;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kikiutils/mongoose",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.3.1",
|
|
4
4
|
"description": "A Mongoose plugin for enhanced JSON normalization and common schema creation, with built-in support for pagination and automatic Decimal128 conversion.",
|
|
5
5
|
"author": "kiki-kanri",
|
|
6
6
|
"license": "MIT",
|
|
@@ -59,21 +59,21 @@
|
|
|
59
59
|
"dependencies": {
|
|
60
60
|
"decimal.js": "^10.5.0",
|
|
61
61
|
"lodash": "^4.17.21",
|
|
62
|
-
"mongoose": "^8.
|
|
62
|
+
"mongoose": "^8.13.0",
|
|
63
63
|
"mongoose-aggregate-paginate-v2": "^1.1.4",
|
|
64
64
|
"mongoose-paginate-v2": "^1.9.0",
|
|
65
|
-
"type-fest": "^4.
|
|
65
|
+
"type-fest": "^4.38.0"
|
|
66
66
|
},
|
|
67
67
|
"devDependencies": {
|
|
68
68
|
"@kikiutils/changelogen": "^0.8.0",
|
|
69
|
-
"@kikiutils/eslint-config": "^0.
|
|
69
|
+
"@kikiutils/eslint-config": "^0.12.0",
|
|
70
70
|
"@kikiutils/tsconfigs": "^3.0.3",
|
|
71
71
|
"@types/jest": "^29.5.14",
|
|
72
72
|
"@types/lodash": "^4.17.16",
|
|
73
|
-
"@types/node": "^22.13.
|
|
73
|
+
"@types/node": "^22.13.13",
|
|
74
74
|
"jest": "^29.7.0",
|
|
75
|
-
"ts-jest": "^29.
|
|
76
|
-
"ts-project-builder": "^3.4.
|
|
75
|
+
"ts-jest": "^29.3.0",
|
|
76
|
+
"ts-project-builder": "^3.4.3",
|
|
77
77
|
"tslib": "^2.8.1"
|
|
78
78
|
}
|
|
79
79
|
}
|
package/src/utils.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { mongo } from 'mongoose';
|
|
1
2
|
import mongoose, { Types } from 'mongoose';
|
|
2
3
|
import mongooseAggregatePaginate from 'mongoose-aggregate-paginate-v2';
|
|
3
4
|
import mongoosePaginate from 'mongoose-paginate-v2';
|
|
@@ -10,6 +11,32 @@ import type { BuildMongooseModelOptions } from './types/options';
|
|
|
10
11
|
|
|
11
12
|
export type DoNotRemoveOrUseThisType = typeof setCustomMongooseOptions;
|
|
12
13
|
|
|
14
|
+
/**
|
|
15
|
+
* Asserts that a Mongoose update operation was successful by checking that it was acknowledged
|
|
16
|
+
* and that at least the expected number of documents were modified.
|
|
17
|
+
*
|
|
18
|
+
* This function is intended for use with `updateOne`, `updateMany`, or any update operation
|
|
19
|
+
* that returns a MongoDB `UpdateResult`.
|
|
20
|
+
*
|
|
21
|
+
* @template T - The shape of the document being updated.
|
|
22
|
+
* @param updatePromise - A promise returned from a Mongoose update operation.
|
|
23
|
+
* @param expectedModifiedCount - The minimum number of documents expected to be modified. Defaults to 1.
|
|
24
|
+
* @throws Will throw an error if:
|
|
25
|
+
* - The operation was not acknowledged by MongoDB,
|
|
26
|
+
* - Fewer documents were modified than expected.
|
|
27
|
+
*/
|
|
28
|
+
export async function assertMongooseUpdateSuccess<T extends mongo.BSON.Document>(
|
|
29
|
+
updatePromise: Promise<mongo.UpdateResult<T>>,
|
|
30
|
+
expectedModifiedCount = 1,
|
|
31
|
+
) {
|
|
32
|
+
const updateResult = await updatePromise;
|
|
33
|
+
if (!updateResult.acknowledged) throw new Error('Update was not acknowledged.');
|
|
34
|
+
if (updateResult.modifiedCount < expectedModifiedCount) {
|
|
35
|
+
// eslint-disable-next-line style/max-len
|
|
36
|
+
throw new Error(`Expected to modify at least ${expectedModifiedCount} document(s), but modified ${updateResult.modifiedCount}.`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
13
40
|
/**
|
|
14
41
|
* Builds and returns a Mongoose model with specified schema and options.
|
|
15
42
|
*
|