Serializing JSON value having Bigint - pg-promise

I have a JSON value as a parameter to one of my query, This parameter contains Bigint inside the JSON internally pg-promise uses JSON.stringfy() on line 80 utils.js for 10.7.1 version which would break, i am fixing this by adding
return JSON.stringify(val, (key, value) =>
typeof value === 'bigint'
? value.toString()
: value // return everything else unchanged
);
is there any other way for this?
Adding code for completion:
payloads = [{ "d": 1n }];
await this.#writerPG.tx((transaction) => {
payloads.map((p) => transaction.none(this.#queries.Enqueue, [p]));
return transaction.batch;
});
Error received:
(node:65560) UnhandledPromiseRejectionWarning: TypeError: Do not know how to serialize a BigInt
at JSON.stringify (<anonymous>)
at prepareObject (/Users/~/Documents/Git/Personal/pg-queue/node_modules/pg/lib/utils.js:80:15)
at prepareValue (/Users/~/Documents/Git/Personal/pg-queue/node_modules/pg/lib/utils.js:65:12)
at prepareValueWrapper (/Users/~/Documents/Git/Personal/pg-queue/node_modules/pg/lib/utils.js:181:12)
at Array.map (<anonymous>)
at Query.prepare (/Users/~/Documents/Git/Personal/pg-queue/node_modules/pg/lib/query.js:202:35)
at Query.submit (/Users/~/Documents/Git/Personal/pg-queue/node_modules/pg/lib/query.js:155:12)
at Client._pulseQueryQueue (/Users/~/Documents/Git/Personal/pg-queue/node_modules/pg/lib/client.js:472:45)
at Client.query (/Users/~/Documents/Git/Personal/pg-queue/node_modules/pg/lib/client.js:567:10)
at /Users/~/Documents/Git/Personal/pg-queue/node_modules/pg-promise/lib/query.js:156:27

Related

omit empty strings fields mongoose

I have the following schema:
const mySchema = new mongoose.Schema({
x: String,
y: String
})
when a user from the front-end requests in his body:
req.body = {
'x' : '',
'y': ''
}
this results in creating a field in MongoDB, but with an empty string.
I need a way to prevent this behavior by setting the empty strings to be undefined somehow.
Is there such an option in Mongoose? or do I have to predict my own middlewares for that?
You could use the set method for Mongoose Schemas:
const mySchema = new mongoose.Schema(
{
myAttribute: {
type: String,
set: (attribute: string) => attribute === '' ? undefined : attribute,
},
},
{ strict: 'throw' },
);
This will unset the field if the string equals ''.
Use this to trim the strings:
set: (a: string) => a?.trim() === '' ? undefined : a
You don't need mongoose, or a middleware to handle this. You can just write a quick few lines to check for empty values and exclude them from the MongoDB write operation.
Ex:
const newEntry = Object.entries(req.body).reduce((obj, [key, value]) => {
if (value) obj[key] = value
return obj
}, {})
In this example, I convert the req.body into an array using Object.entries and iterate over it with the Array.reduce method, wherein I add key:value pairs to a new object if there is a value to add. Since an empty string value is falsey I can do a simple if check on the value. I then assign the return of the reduce method to the variable newEntry. Then I would then take the new entry and create the MongoDB document with it.
This could be extracted into a helper method and reused in any of your routes that need to check remove empty values from an object.
Docs on Array.reduce
Docs on Object.entries

instantsearch.js with error in javascript console => RangeError: Invalid array length

I have this error on javascript console for a long time.
It is related with instantsearch.js and the paginator.
Can anyone help?
range.ts:18 Uncaught (in promise) RangeError: Invalid array length
at Ie (range.ts:18)
at t.value (Paginator.js:31)
at Object.render (connectPagination.js:147)
at index.ts:481
at Array.forEach (<anonymous>)
at Object.render (index.ts:472)
at InstantSearch.ts:510
at defer.ts:26
This error appear when the page load and I initialize the search instance.
Ok. Here is what you need to do.
Algolia Documentation
Code Sample
Finally. Inside your custom search client do this. Am using a sample computed property as my searchClient. Which will be cached thus not firing another request to Algolia.
search(requests) {
if (requests.every(({ params }) => !params.query)) {
// Here we have to do something else...
// Since the query is empty i.e. ""
return Promise.resolve({
results: requests.map(() => ({
// When an empty search is detected, a formatted response must be returned
// with atleast below properties.
// Otherwise;
// RangeError is generated if all other fields aren't provided.
hits: [],
nbHits: 0,
nbPages: 0,
page: 0,
facets: [],
processingTimeMS: 0,
hitsPerPage: 0,
exhaustiveNbHits: false,
query: "",
params: "",
})),
});
}
// Else query using provided input
return algoliaClient.search(requests);
},
};
}

Mongoose Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters

I am creating a user using Mongoose, and I want to use my own _id. I thought that you could convert any string to an ObjectId with the following code: mongoose.Types.ObjectId('4fhTTRkUYNPBUSiYIhz8YHZ9wQ02'). This is what several other Stack Overflow answers have suggested. However, when I use this code in Node, I get the following error: Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters.
What am I doing wrong?
router.post("/create_user", (req, res) => {
const id = req.body.id;
console.log("/create_user id : ", id); // <-- logging successfully '4fhTTRkUYNPBUSiYIhz8YHZ9wQ02'
User.create({
_id: mongoose.Types.ObjectId(id), // <-- generating error
name: "Joe"
})
.then((u) => {
return res.json({ user: u });
})
.catch((err) => {
console.log("/create_user error : ", err);
return res.json({ error: err });
});
});
I thought that you could convert any string to an ObjectId
This is not the case, only some strings are valid ObjectIds.

Ionic2 Native Storage storing/retrieving Arrays

I have an Ionic app in which I store an Array with Native-Storage.
This Array is an array of objects.
I stored it like this:
>>> array1: CertainType[] With at least 50 shuffled elements
this.nativeStorage.setItem('array1', { property: array1 })
.then(
() => { console.log('array1 stored') },
error => { console.log('array1 not Stored',error)
});
I retrieve the item like this:
this.nativeStorage.getItem('array1').then(
array1 => {
//On the Sucess of getting Array1 use it to create Array2
array2 = array1.splice(0,5); //<-- MY PROBLEM IS HERE
},
error => {
console.error('Error Getting Array', error);
}
);
I keep getting the Error of
I thought its because the process of storing and retrieving was messing with the type of the array, etc.
I tried to do casting:
..array1 as CertainType[]
-- EDITED>>
I tried stringfying and JSONparsing.
this.nativeStorage.setItem('array1', { property: JSON.stringify(array1)}).then(. . . .
array2 = JSON.parse(array1);
Throw this error:
ERROR Error: Uncaught (in promise): SyntaxError: Unexpected token o in JSON at position 1
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
But i keep getting the same error on the splice().
If I not use the logic of storing, the code runs just fine.... Any clues. What am I missing? :/
Use JSON stringify before store in localStorage cause it will return a promise
just do this for example :
​var test = { test: "thing", test2: "thing2", test3: [0, 2, 44] }​​​​​​​;
localStorage.setItem("test", JSON.stringify(test));
var test2 = localStorage.getItem("test");
test = JSON.parse(test2);
The Ionic Native Storage Documentation confused me.
this.nativeStorage.setItem('myitem', {property: 'value', anotherProperty: 'anotherValue'})
.then(
() => console.log('Stored item!'),
error => console.error('Error storing item', error)
);
I sticked to the book and use almost equal code on my app. But that word "property" over there was breaking my floor.
The good contributor above me, insisted (thank god) on the use of JSON.stringify and JSON.parse to save and retrieve the data.
So I did, but kept getting errors. Then I realized: when I tried to retrieve the data, my Array was stored on an Object. Ok! But UNDER a p-r-o-p-e-r-y attribute..
If I did get my array1 using array1.property I would get what I was looking for.
In the end, just a little change will make it work like a clock:
this.nativeStorage.setItem('array1', JSON.stringfy(array)})
.then(. . .
this.storage.get('array').then( array1 => {
console.log(JSON.parse(array1));

Validating Mongoose Mixed schema type

I have a schema:
// Schema
var Product = new Schema({
data: {
type: mongoose.Schema.Types.Mixed
},
created: {
type: Date,
'default' : Date.now
}
});
The 'data' field is used to store a json string which will vary. I do however want to perform some basic validation such as length etc.. However doing this:
// Validation
Product.path('data').validate(function (value) {
console.log(value);
return value.length > 0;
}, 'Data cannot be blank');
Throws an error about data not existing:
TypeError: Cannot read property 'length' of undefined
What is the best way to do this?
You are treating "value" as an object without checking if it really is. Try with this:
if(typeof value !== "undefined" && value !== null)
{
return value.length > 0
}