How to escape $ while inserting inside mongoDB - node.js

I have a large object which I have no control over, fields might vary a lot:
Error ==>> { MongoError: The dollar ($) prefixed field '$' in
'value.external.originalRequest.rawRequest.ns2:LoadData.Orders.0.Order.0.TotalThirdPartyCharge.0.CurrencyValue.0.$'
is not valid for storage. 0|lt-check | at
Function.MongoError.create
(/home/ops/lt-checkin-api/node_modules/mongodb-core/lib/error.js:31:11)
0|lt-check | at
/home/ops/lt-checkin-api/node_modules/mongodb-core/lib/connection/pool.js:497:72
0|lt-check | at authenticateStragglers
(/home/ops/lt-checkin-api/node_modules/mongodb-core/lib/connection/pool.js:443:16)
0|lt-check | at Connection.messageHandler
(/home/ops/lt-checkin-api/node_modules/mongodb-core/lib/connection/pool.js:477:5)
0|lt-check | at Socket.
(/home/ops/lt-checkin-api/node_modules/mongodb-core/lib/connection/connection.js:333:22)
0|lt-check | at Socket.emit (events.js:159:13) 0|lt-check | at
addChunk (_stream_readable.js:265:12) 0|lt-check | at
readableAddChunk (_stream_readable.js:252:11) 0|lt-check | at
Socket.Readable.push (_stream_readable.js:209:10) 0|lt-check | at
TCP.onread (net.js:608:20) 0|lt-check | name: 'MongoError',
0|lt-check | message: 'The dollar ($) prefixed field \'$\' in
\'value.external.originalRequest.rawRequest.ns2:LoadData.Orders.0.Order.0.TotalThirdPartyCharge.0.CurrencyValue.0.$\'
is not valid for storage.', 0|lt-check | ok: 0, 0|lt-check |
errmsg: 'The dollar ($) prefixed field \'$\' in
\'value.external.originalRequest.rawRequest.ns2:LoadData.Orders.0.Order.0.TotalThirdPartyCharge.0.CurrencyValue.0.$\'
is not valid for storage.', 0|lt-check | code: 52, 0|lt-check |
codeName: 'DollarPrefixedFieldName' }
Here the key causing the error:
"rawRequest": {
"ns2:LoadData": {
"$": {
"xmlns:ns2": "http://schemas.3gtms.com/tms/v1/tns"
},
"BatchInfo": [
{
"$": {
"xmlns": ""
},
As there are multiple keys starting with $.
Is there a setting in mongoose or mongoDB itself to insert anything without validating the request coming in.

Was going to create a new plugin but #Anirudh helped me find this package in the comment
https://www.npmjs.com/package/mongo-escape
To use it, just before your insert query escape you object using the above package.
var escapeForMongo = require('mongo-escape').escape;
userInput = escapeForMongo({
'foo': 'bar',
'ba.z': {
'$in': 'quz'
}
})

function escapeMongo(obj) {
return JSON.parse(
JSON.stringify(obj),
function(p, v) {
if ((p[0] === '$') || (p.includes('.'))) {
this[p.replace(/\$/g, '\uFF04').replace(/\./g, '\uFF0E')] = v;
return;
}
return v;
}
)
}
userInput = {
'foo': 'bar',
'ba.z': {
'$in': 'quz'
}
}
console.log(userInput)
console.log(escapeMongo(userInput))
You can use JSON.parse to process a JSON string before creating object.

Related

Switching Storybook from Webpack to Vita in Gatsby app

I work on a Gatsby project and I'm hoping to run our Storybook with Vita instead of our existing Webpack setup. I'm clearly not doing it right.
I added the plugins:
"#storybook/builder-vite": "^0.4.2",
"#vitejs/plugin-react": "^3.1.0",
"vite": "^4.1.1",
I also added our aliases by importing my tsconfigand converting the paths to the right format.
Although most of my attempts to run it resulted in about 1000 instances of
Failed to resolve import "react/jsx-dev-runtime" from "react/jsx-dev-runtime". Does the file exist?
it's actually running now. And it booted up WAY faster than it used to.
The only issue appears to be that it's not reloading, not at all. I make a change in a component, or a change in a story, and there is zero output in the terminal running storybook.
Although I do notice that this run, although it looks like it's working in the browser, does still give only these two errors:
Failed to resolve dependency: react/jsx-runtime, present in 'optimizeDeps.include'
Failed to resolve dependency: react/jsx-dev-runtime, present in 'optimizeDeps.include'
How can I fix this? I'm so close!
I've tried...
const react = require('#vitejs/plugin-react');
//...
module.exports = {
// ...
async viteFinal(config) {
return mergeConfig(config, {
// is this where this goes?
plugins: [
react({
jsxRuntime: 'classic',
}),
],
resolve: { alias: aliasPathsVite },
},
})
},
}
Which does open Storybook in the browser, but it doesn't load, and the terminal gives endless instances of:
10:30:38 AM [vite] Internal server error: Transform failed with 2 errors:
Typography/Links.tsx:3:4: ERROR: The symbol "prevRefreshReg" has already been declared
Typography/Links.tsx:4:4: ERROR: The symbol "prevRefreshSig" has already been declared
Plugin: vite:esbuild
File: Typography/Links.tsx:1:42
The symbol "prevRefreshReg" has already been declared
1 | import RefreshRuntime from "/#react-refresh";let prevRefreshReg;let prevRefreshSig;if (import.meta.hot) { if (!window.__vite_plugin_react_preamble_installed__) { throw new Error( "#vitejs/plugin-react can't detect preamble. Something is wrong. " + "See https://github.com/vitejs/vite-plugin-react/pull/11#discussion_r430879201" ); } prevRefreshReg = window.$RefreshReg$; prevRefreshSig = window.$RefreshSig$; window.$RefreshReg$ = (type, id) => { RefreshRuntime.register(type, "Typography/Links.tsx" + " " + id) }; window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;}var _jsxFileName = "Typography/Links.tsx";
2 | import RefreshRuntime from "/#react-refresh";
3 | let prevRefreshReg;
| ^
4 | let prevRefreshSig;
5 | if (import.meta.hot) {
The symbol "prevRefreshSig" has already been declared
2 | import RefreshRuntime from "/#react-refresh";
3 | let prevRefreshReg;
4 | let prevRefreshSig;
| ^
5 | if (import.meta.hot) {
6 | if (!window.__vite_plugin_react_preamble_installed__) {
at failureErrorWithLog (node_modules/esbuild/lib/main.js:1604:15)
at node_modules/esbuild/lib/main.js:837:29
at responseCallbacks.<computed> (node_modules/esbuild/lib/main.js:701:9)
at handleIncomingPacket (node_modules/esbuild/lib/main.js:756:9)
at Socket.readFromStdout (node_modules/esbuild/lib/main.js:677:7)
at Socket.emit (node:events:513:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)
at Pipe.onStreamRead (node:internal/stream_base_commons:190:23)
I've tried...
module.exports = {
// ...
async viteFinal(config) {
return mergeConfig(config, {
resolve: {
alias: {
...aliasPathsVite,
'react/jsx-runtime': path.join(
__dirname,
'node-modules/react/jsx-runtime'
),
},
optimizeDeps: {
include: ['react/jsx-runtime']
}
},
})
},
}
which opens a non-working Storybook in the browser, and the terminal says this hundreds of times
Failed to resolve import "react/jsx-dev-runtime" from "react/jsx-dev-runtime". Does the file exist?
Then some of these:
[vite] error while updating dependencies:
Error: ENOENT: no such file or directory, rename 'node_modules/.vite-storybook/deps_temp' -> 'node_modules/.vite-storybook/deps'
at renameSync (node:fs:1030:3)
at Object.commit (file:///node_modules/vite/dist/node/chunks/dep-3007b26d.js:42874:19)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async commitProcessing (file:///node_modules/vite/dist/node/chunks/dep-3007b26d.js:42348:17)
at async runOptimizer (file:///node_modules/vite/dist/node/chunks/dep-3007b26d.js:42386:17)
And then a bunch of issues importing CSS files, like this one
10:45:29 AM [vite] Internal server error: Failed to resolve import "./header.css" from "node_modules/#storybook/mdx1-csf/dist/esm/stories/Header.js?v=ec48b265". Does the file exist?
Have you tried something like this?
resolve: {
alias: {
'react/jsx-runtime': 'react/jsx-runtime.js',
},
},
Source: https://github.com/vitejs/vite/issues/6215
Also:
optimizeDeps.include: ['react/jsx-runtime']
Another way can be tweaking the configuration of #vitejs/plugin-react:
import react from '#vitejs/plugin-react';
export default defineConfig({
plugins: [
react({
jsxRuntime: 'classic',
}),
]
});

BigQuery Error while running query on prod

So this is the error I am getting
ApiError: Syntax error: Missing whitespace between literal and alias at [2:18]
1|index | at new ApiError (/home/sahil_bswgames_com/LudoRConfData/node_modules/#google-cloud/common/build/src/util.js:75:15)
1|index | at /home/sahil_bswgames_com/LudoRConfData/node_modules/#google-cloud/bigquery/build/src/bigquery.js:1074:23
1|index | at /home/sahil_bswgames_com/LudoRConfData/node_modules/#google-cloud/common/build/src/util.js:412:25
1|index | at Util.handleResp (/home/sahil_bswgames_com/LudoRConfData/node_modules/#google-cloud/common/build/src/util.js:161:9)
1|index | at /home/sahil_bswgames_com/LudoRConfData/node_modules/#google-cloud/common/build/src/util.js:534:22
1|index | at onResponse (/home/sahil_bswgames_com/LudoRConfData/node_modules/retry-request/index.js:240:7)
1|index | at /home/sahil_bswgames_com/LudoRConfData/node_modules/teeny-request/build/src/index.js:226:13
1|index | at processTicksAndRejections (internal/process/task_queues.js:97:5) {
1|index | code: undefined,
1|index | errors: [
1|index | {
1|index | reason: 'invalidQuery',
1|index | location: 'query',
1|index | message: 'Syntax error: Missing whitespace between literal and alias at [2:18]'
1|index | }
1|index | ],
and following is my query
SELECT assetId, date, uniqueUsers as uniqueUsershavingP1 FROM table WHERE date between '2022-10-01' and '2022-10-25" and event= "abc"
What is wrong in this query, because query is running perfectly on local but not on prod
I have tried to put table name in quotes as suggested by many articles bt that did'nt work either

New to Web development not sure how to fix reactjs errors [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
These is a long page full for error messages and I cannot get hold of the person teaching this class been 2 weeks. I tried redoing it but I still got the same messages I do not know how or what to do in order to fix them. Here is the git hub link: https://github.com/SadiaSanam/petshop
And these are the messages, how to I fix it? Because some of those pages I cannot even find..
TypeError: path.split is not a function
get
C:/Users/sadia/OneDrive/SheCodes/Full stack/app/src/utils/get.ts:6
TypeError: path.split is not a function
get
C:/Users/sadia/OneDrive/SheCodes/Full stack/app/src/utils/get.ts:6
3 | import isUndefined from './isUndefined';
4 |
5 | export default (obj: any = {}, path: string, defaultValue?: unknown) => {
> 6 | const result = compact(path.split(/[,[\].]+?/)).reduce(
7 | (result, key) => (isNullOrUndefined(result) ? result : result[key]),
8 | obj,
9 | );
View compiled
(anonymous function)
C:/Users/sadia/OneDrive/SheCodes/Full stack/app/src/useForm.ts:967
964 |
965 | const register: UseFormRegister<TFieldValues> = React.useCallback(
966 | (name, options) => {
> 967 | const isInitialRegister = !get(fieldsRef.current, name);
| ^ 968 |
969 | set(fieldsRef.current, name, {
970 | _f: {
View compiled
Login
C:/Users/sadia/OneDrive/SheCodes/Full stack/app/petshop/src/components/Login.js:88
85 | <div className='form-control'>
86 |
87 | <label htmlFor='email'>Email</label>
> 88 | <input type='email' name='email' id='email' ref={register( {required:true}) } />
| ^ 89 | { errors.email ? <span className='err'> email is required!</span> : null }
90 |
91 | <label htmlFor='password'>Password</label>
View compiled
renderWithHooks
C:/Users/sadia/OneDrive/SheCodes/Full stack/app/petshop/node_modules/react-dom/cjs/react-dom.development.js:14985
14982 | }
14983 | }
14984 |
> 14985 | var children = Component(props, secondArg); // Check if there was a render phase update
| ^ 14986 |
14987 | if (didScheduleRenderPhaseUpdateDuringThisPass) {
14988 | // Keep rendering in a loop for as long as render phase updates continue to
View compiled
mountIndeterminateComponent
C:/Users/sadia/OneDrive/SheCodes/Full stack/app/petshop/node_modules/react-dom/cjs/react-dom.development.js:17811
17808 |
17809 | setIsRendering(true);
17810 | ReactCurrentOwner$1.current = workInProgress;
> 17811 | value = renderWithHooks(null, workInProgress, Component, props, context, renderLanes);
| ^ 17812 | setIsRendering(false);
17813 | } // React DevTools reads this flag.
17814 |
View compiled
beginWork
C:/Users/sadia/OneDrive/SheCodes/Full stack/app/petshop/node_modules/react-dom/cjs/react-dom.development.js:19049
19046 | switch (workInProgress.tag) {
19047 | case IndeterminateComponent:
19048 | {
> 19049 | return mountIndeterminateComponent(current, workInProgress, workInProgress.type, renderLanes);
| ^ 19050 | }
19051 |
19052 | case LazyComponent:
View compiled
HTMLUnknownElement.callCallback
C:/Users/sadia/OneDrive/SheCodes/Full stack/app/petshop/node_modules/react-dom/cjs/react-dom.development.js:3945
3942 | function callCallback() {
3943 | didCall = true;
3944 | restoreAfterDispatch();
> 3945 | func.apply(context, funcArgs);
| ^ 3946 | didError = false;
3947 | } // Create a global error event handler. We use this to capture the value
3948 | // that was thrown. It's possible that this error handler will fire more
View compiled
invokeGuardedCallbackDev
C:/Users/sadia/OneDrive/SheCodes/Full stack/app/petshop/node_modules/react-dom/cjs/react-dom.development.js:3994
3991 | // errors, it will trigger our global error handler.
3992 |
3993 | evt.initEvent(evtType, false, false);
> 3994 | fakeNode.dispatchEvent(evt);
| ^ 3995 |
3996 | if (windowEventDescriptor) {
3997 | Object.defineProperty(window, 'event', windowEventDescriptor);
View compiled
invokeGuardedCallback
C:/Users/sadia/OneDrive/SheCodes/Full stack/app/petshop/node_modules/react-dom/cjs/react-dom.development.js:4056
4053 | function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
4054 | hasError = false;
4055 | caughtError = null;
> 4056 | invokeGuardedCallbackImpl$1.apply(reporter, arguments);
4057 | }
4058 | /**
4059 | * Same as invokeGuardedCallback, but instead of returning an error, it stores
View compiled
beginWork$1
C:/Users/sadia/OneDrive/SheCodes/Full stack/app/petshop/node_modules/react-dom/cjs/react-dom.development.js:23964
23961 | } // Run beginWork again.
23962 |
23963 |
> 23964 | invokeGuardedCallback(null, beginWork, null, current, unitOfWork, lanes);
| ^ 23965 |
23966 | if (hasCaughtError()) {
23967 | var replayError = clearCaughtError(); // `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`.
View compiled
performUnitOfWork
C:/Users/sadia/OneDrive/SheCodes/Full stack/app/petshop/node_modules/react-dom/cjs/react-dom.development.js:22776
22773 |
22774 | if ( (unitOfWork.mode & ProfileMode) !== NoMode) {
22775 | startProfilerTimer(unitOfWork);
> 22776 | next = beginWork$1(current, unitOfWork, subtreeRenderLanes);
| ^ 22777 | stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
22778 | } else {
22779 | next = beginWork$1(current, unitOfWork, subtreeRenderLanes);
View compiled
workLoopSync
C:/Users/sadia/OneDrive/SheCodes/Full stack/app/petshop/node_modules/react-dom/cjs/react-dom.development.js:22707
22704 | function workLoopSync() {
22705 | // Already timed out, so perform work without checking if we need to yield.
22706 | while (workInProgress !== null) {
> 22707 | performUnitOfWork(workInProgress);
22708 | }
22709 | }
22710 |
View compiled
renderRootSync
C:/Users/sadia/OneDrive/SheCodes/Full stack/app/petshop/node_modules/react-dom/cjs/react-dom.development.js:22670
22667 |
22668 | do {
22669 | try {
> 22670 | workLoopSync();
| ^ 22671 | break;
22672 | } catch (thrownValue) {
22673 | handleError(root, thrownValue);
View compiled
performSyncWorkOnRoot
C:/Users/sadia/OneDrive/SheCodes/Full stack/app/petshop/node_modules/react-dom/cjs/react-dom.development.js:22293
22290 | }
22291 | } else {
22292 | lanes = getNextLanes(root, NoLanes);
> 22293 | exitStatus = renderRootSync(root, lanes);
| ^ 22294 | }
22295 |
22296 | if (root.tag !== LegacyRoot && exitStatus === RootErrored) {
View compiled
(anonymous function)
C:/Users/sadia/OneDrive/SheCodes/Full stack/app/petshop/node_modules/react-dom/cjs/react-dom.development.js:11327
11324 | var callback = _queue[i];
11325 |
11326 | do {
> 11327 | callback = callback(_isSync2);
| ^ 11328 | } while (callback !== null);
11329 | }
11330 | });
View compiled
unstable_runWithPriority
C:/Users/sadia/OneDrive/SheCodes/Full stack/app/petshop/node_modules/scheduler/cjs/scheduler.development.js:468
465 | currentPriorityLevel = priorityLevel;
466 |
467 | try {
> 468 | return eventHandler();
| ^ 469 | } finally {
470 | currentPriorityLevel = previousPriorityLevel;
471 | }
View compiled
runWithPriority$1
C:/Users/sadia/OneDrive/SheCodes/Full stack/app/petshop/node_modules/react-dom/cjs/react-dom.development.js:11276
11273 |
11274 | function runWithPriority$1(reactPriorityLevel, fn) {
11275 | var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
> 11276 | return Scheduler_runWithPriority(priorityLevel, fn);
11277 | }
11278 | function scheduleCallback(reactPriorityLevel, callback, options) {
11279 | var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
View compiled
flushSyncCallbackQueueImpl
C:/Users/sadia/OneDrive/SheCodes/Full stack/app/petshop/node_modules/react-dom/cjs/react-dom.development.js:11322
11319 | try {
11320 | var _isSync2 = true;
11321 | var _queue = syncQueue;
> 11322 | runWithPriority$1(ImmediatePriority$1, function () {
| ^ 11323 | for (; i < _queue.length; i++) {
11324 | var callback = _queue[i];
11325 |
View compiled
flushSyncCallbackQueue
C:/Users/sadia/OneDrive/SheCodes/Full stack/app/petshop/node_modules/react-dom/cjs/react-dom.development.js:11309
11306 | Scheduler_cancelCallback(node);
11307 | }
11308 |
> 11309 | flushSyncCallbackQueueImpl();
11310 | }
11311 |
11312 | function flushSyncCallbackQueueImpl() {
View compiled
discreteUpdates$1
C:/Users/sadia/OneDrive/SheCodes/Full stack/app/petshop/node_modules/react-dom/cjs/react-dom.development.js:22420
22417 | if (executionContext === NoContext) {
22418 | // Flush the immediate callbacks that were scheduled during this batch
22419 | resetRenderTimer();
> 22420 | flushSyncCallbackQueue();
| ^ 22421 | }
22422 | }
22423 | }
View compiled
discreteUpdates
C:/Users/sadia/OneDrive/SheCodes/Full stack/app/petshop/node_modules/react-dom/cjs/react-dom.development.js:3756
3753 | isInsideEventHandler = true;
3754 |
3755 | try {
> 3756 | return discreteUpdatesImpl(fn, a, b, c, d);
| ^ 3757 | } finally {
3758 | isInsideEventHandler = prevIsInsideEventHandler;
3759 |
View compiled
dispatchDiscreteEvent
C:/Users/sadia/OneDrive/SheCodes/Full stack/app/petshop/node_modules/react-dom/cjs/react-dom.development.js:5889
5886 | flushDiscreteUpdatesIfNeeded(nativeEvent.timeStamp);
5887 | }
5888 |
> 5889 | discreteUpdates(dispatchEvent, domEventName, eventSystemFlags, container, nativeEvent);
5890 | }
5891 |
5892 | function dispatchUserBlockingUpdate(domEventName, eventSystemFlags, container, nativeEvent) {
View compiled
TO use react-hook-forms, theres some fix to work:
The inputs fields calls the register function. This function has 2 params:
register(field_name <- string, options <- object);
In your case, you need to call it like that:
<input type='email' name='email' id='email' ref={register("email", {required:true}) } />
<input type='password' name='password' id='password'
ref={register("password", {required:true, minLength:6, maxLength: 10} )} />
You're calling the error object the wrong way. Thats how you should call it:
const { register, handleSubmit, formState: { errors }, reset } = useForm();
The last error I found after the fix is about the way you call register function.
You are setting the register at the ref property. According to the docs, you should just set the register in the component, and this will return all the props:
<input type='email' id='email' {...register("email", {required:true}) } />
Here at the Sources, you can read and deep in "why am I doing this?" =):
register():
https://react-hook-form.com/api/useform/register
errors:
https://react-hook-form.com/api/useformstate/errormessage
I'll add here some tips to help you found the solution to new errors:
Make a path to discover where to focus: When you have an error, you need to found exactly what's causing it. In your case, the console was accusing a file that isn't even in your main folders (that was a dependency). In that case, remove code, try to delete some code, and see if the project works. If works, you now is somewhere there, and do again filtering the removed code.
Go to the official docs/demos and compare your code: I've never used react-hook-forms, But a look at the docs helps me to find the errors.

How do I use local TypeScript with npm on an isolated file in a larger project?

I have an Expo TypeScript project with some scratch TypeScript files that I would like to test by running tsc (and then node on the emitted JS). But doing so results in unexpected errors, and fails to report legitimate expected TS errors.
I have a (correctly, I believe) configured TypeScript locally installed with npm, as confirmed by
$ ./node_modules/typescript/bin/tsc --version
Version 3.5.3
but when I try use tsc on a TypeScript file I get unexpected errors, such as those listed below following execution of
npx tsc somefile.ts
Moreover, tsc (at least when invoked as above) fails to emit any expected errors or compiler warnings, such as should be generated from, for example
let foo: number = 5
foo = null
Nonetheless, the expected _somefile.js is generated and runs as expected (ignoring errors).
How do I get tsc to detect errors in my .ts file, and avoid having it report numerous errors in other modules associated with my project installation?
Output from npx tsc somefile.ts, abbreviated:
node_modules/#types/react-native/globals.d.ts:40:15 - error TS2300: Duplicate identifier 'FormData'.
40 declare class FormData {
~~~~~~~~
node_modules/typescript/lib/lib.dom.d.ts:5353:11
5353 interface FormData {
~~~~~~~~
'FormData' was also declared here.
node_modules/typescript/lib/lib.dom.d.ts:5363:13
5363 declare var FormData: {
~~~~~~~~
and here.
node_modules/#types/react-native/globals.d.ts:85:5 - error TS2717: Subsequent property declarations must have the same type. Property 'body' must be of type 'BodyInit', but here has type 'string | ArrayBuffer | DataView | Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | Blob | FormData'.
85 body?: BodyInit_;
~~~~
node_modules/typescript/lib/lib.dom.d.ts:1413:5
1413 body?: BodyInit | null;
~~~~
'body' was also declared here.
node_modules/#types/react-native/globals.d.ts:111:14 - error TS2300: Duplicate identifier 'RequestInfo'.
111 declare type RequestInfo = Request | string;
~~~~~~~~~~~
node_modules/typescript/lib/lib.dom.d.ts:18568:6
18568 type RequestInfo = Request | string;
~~~~~~~~~~~
'RequestInfo' was also declared here.
node_modules/#types/react-native/globals.d.ts:130:13 - error TS2403: Subsequent variable declarations must have the same type. Variable 'Response' must be of type '{ new (body?: BodyInit, init?: ResponseInit): Response; prototype: Response; error(): Response; redirect(url: string, status?: number): Response; }', but here has type '{ new (body?: string | ArrayBuffer | DataView | Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | Blob | FormData, init?: ResponseInit): Response; prototype: Response; error: () => Response; redirect: (url: string, status?: number) => Res...'.
130 declare var Response: {
~~~~~~~~
node_modules/typescript/lib/lib.dom.d.ts:12463:13
12463 declare var Response: {
~~~~~~~~
'Response' was also declared here.
node_modules/#types/react-native/globals.d.ts:253:14 - error TS2300: Duplicate identifier 'XMLHttpRequestResponseType'.
253 declare type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text";
~~~~~~~~~~~~~~~~~~~~~~~~~~
node_modules/typescript/lib/lib.dom.d.ts:18746:6
18746 type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text";
~~~~~~~~~~~~~~~~~~~~~~~~~~
'XMLHttpRequestResponseType' was also declared here.
[...]
node_modules/typescript/lib/lib.dom.d.ts:18746:6 - error TS2300: Duplicate identifier 'XMLHttpRequestResponseType'.
18746 type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text";
~~~~~~~~~~~~~~~~~~~~~~~~~~
node_modules/#types/react-native/globals.d.ts:253:14
253 declare type XMLHttpRequestResponseType = "" | "arraybuffer" | "blob" | "document" | "json" | "text";
~~~~~~~~~~~~~~~~~~~~~~~~~~
'XMLHttpRequestResponseType' was also declared here.
Found 12 errors.
Contents of tsconfig.json:
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"jsx": "react-native",
"lib": ["dom", "esnext"],
"moduleResolution": "node",
"noEmit": true,
"skipLibCheck": true,
"resolveJsonModule": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"strict": true
}
}
The dependences in project.json:
"dependencies": {
"expo": "^34.0.4",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-native": "https://github.com/expo/react-native/archive/sdk-34.0.0.tar.gz",
"react-native-web": "^0.11.5",
"native-base": "^2.13.4",
"redux": "^4.0.4",
"react-redux": "^7.1.0"
},
These errors occur because both React Native and the standard dom modules define the same types.
Delete whichever of those you aren't using.

Mongoose bulkWrite - Wrong type for 'q'

For my test suite, I want to bulkWrite test info in the database, and then bulk delete any of the test info entered throughout the test to come back to a clean slate. I do so by running a bulkWrite on the db to which I pass the content of a JSON file loaded via nodeJS's require statement.
The problem is that for the dataset
[ { deleteOne: { username: 'test-author' } } ]
passed to models[key].collection.bulkWrite(action[key]), where key is the name of the model of interest and action is the JSON file,I get the following error:
{ MongoError: Wrong type for 'q'. Expected a object, got a null.
at Function.MongoError.create (/var/www/website/server/node_modules/mongodb-core/lib/error.js:31:11)
at /var/www/website/server/node_modules/mongodb-core/lib/connection/pool.js:483:72
at authenticateStragglers (/var/www/website/server/node_modules/mongodb-core/lib/connection/pool.js:429:16)
at Connection.messageHandler (/var/www/website/server/node_modules/mongodb-core/lib/connection/pool.js:463:5)
at Socket.<anonymous> (/var/www/website/server/node_modules/mongodb-core/lib/connection/connection.js:339:20)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
at Socket.Readable.push (_stream_readable.js:134:10)
at TCP.onread (net.js:548:20)
name: 'MongoError',
message: 'Wrong type for \'q\'. Expected a object, got a null.',
ok: 0,
errmsg: 'Wrong type for \'q\'. Expected a object, got a null.',
code: 14,
codeName: 'TypeMismatch' }
I have done some research and have been unable to find a solution to this problem. The error itself is pretty meaningless, so I can't grasp much out of it. Any idea how to solve the problem?
Any help would be greatly appreciated!
Cheers!
As per the MongoDB API, the deleteOne, deleteMany, updateOne, updateMany, replaceOne, and replaceMany operation requires to have a property filter which acts as the filter for the query.
However Mongoose's API shows the following (mistaken) example:
Character.bulkWrite([
...
{
deleteOne: {
{ name: 'Eddard Stark' }
}
}
]).then(handleResult);
Hence, the data sent over changes from:
[{
"deleteOne": { "username": "test-author" }
}]
to
[{
"deleteOne": { "filter": { "username": "test-author" }}
}]
I'll make sure to pass the message along to the mongoosejs dev group.

Resources