Comments (19)
The reason you are seeing this is because you are trying to fetch a Decimal128 object, not the actual decimal value inside it. To fix this, I think you can remove the set
property, and change your get
property to:
get: v => (+v.toString()).toFixed(4)
For reference: https://stackoverflow.com/questions/65722311/mongoose-insert-decimal128-data-in-db-saved-as-string-for-required-nested-docume
from mongoose.
The reason you are seeing this is because you are trying to fetch a Decimal128 object, not the actual decimal value inside it. To fix this, I think you can remove the
set
property, and change yourget
property to:get: v => (+v.toString()).toFixed(4)
For reference: https://stackoverflow.com/questions/65722311/mongoose-insert-decimal128-data-in-db-saved-as-string-for-required-nested-docume
I tried to do that v =>(+v.toString().toFixed(4)) and still have the same issue.
I would also really like to avoid converting it to a String at any point since my front end (Flutter) uses a double data type
from mongoose.
Did you try removing the set, and only use the above get method? Also, toFixed() will convert your string back to a decimal number
from mongoose.
Did you try removing the set, and only use the above get method? Also, toFixed() will convert your string back to a decimal number
removing the set? I dropped the collection, restarted everything and created a new record each time I've made changes. I can try it again a little later, maybe I made a typo the first time
from mongoose.
Ohh ok, I understood, you are trying to use the set to directly convert string to decimal128, so removing it might not be a solution
from mongoose.
Just for debugging purpose, can you console.log what does v
and v.toString()
prints? Also, check if this answer is of any help to you (although this is a bit old) - https://stackoverflow.com/questions/61380443/mongodb-returning-with-numberdecimal-in-the-response-of-a-query
from mongoose.
I tried to do that v =>(+v.toString().toFixed(4)) and still have the same issue.
It should be v => (+v.toString()).toFixed(4)
not v =>(+v.toString().toFixed(4))
(the parentheses are wrong), otherwise it will throw an error internally
from mongoose.
I tried to do that v =>(+v.toString().toFixed(4)) and still have the same issue.
It should be
v => (+v.toString()).toFixed(4)
notv =>(+v.toString().toFixed(4))
(the parentheses are wrong), otherwise it will throw an error internally
v => (+v.toString()).toFixed(4) had the same result of: rev: new Decimal128("1.2"),
I tried it again with the same result.
Where can I put the console log to access v? If i do it in my controller it doesn't see it and I didn't think I could do that in the getter or schema?
from mongoose.
I think it can be done in the get method probably
from mongoose.
I think it can be done in the get method probably
I'm not having any luck getting it to console.log in either the
rev: {type: Types.Decimal128,
get: (v) => {
console.log(`${v} print`);
console.log(v.toString());
}
// get: v => (+v.toString()).toFixed(4),
// set: v => (+v.toString()).toFixed(4),
},
when I do a console.log((data.rev).toString) in the controller I get this error:
TypeError: Cannot read properties of undefined (reading 'toString')
Why is the Decimal128 being read as an object? shouldn't Mongoose be set up in a way where you don't have to do extra steps to read in an approved data type?
from mongoose.
when I do a console.log((data.rev).toString) in the controller I get this error:
TypeError: Cannot read properties of undefined (reading 'toString')
Why are you modifying the set method? The set doesn't need to be modified. Like, the return type for the set method should be an Decimal128 object, but you are returning a number. I think the issue is happening because the value is being set wrong, due to which when you are trying to get it, its returning undefined, because I tested it in my local, and for me the get is working fine. I'll suggest you can try removing the set method and only use the get method.
Why is the Decimal128 being read as an object? shouldn't Mongoose be set up in a way where you don't have to do extra steps to read in an approved data type?
Mongoose uses bson library's Decimal128 internally
from mongoose.
the set method is commented out. I modified it because I was trying all options before asking for help even if it didn't seem like it would work.
Where else could it possibly be set? If I remove the set method we still have the issue so is there possibly somewhere else in the program it could be being set wrong? I'm picking up from someone else and I did look first to see if there could be something happening elsewhere but I'm out of ideas as to where it could be happening
from mongoose.
I'll try to look into the cause later on, but for now you can try setting the type of the field to Schema.Types.Decimal128
instead of Types.Decimal128
as that's what is recommended in the doc
from mongoose.
I'll try to look into the cause later on, but for now you can try setting the type of the field to
Schema.Types.Decimal128
instead ofTypes.Decimal128
as that's what is recommended in the doc
I did the Schema.Types.Decimal128 first, then added Types in the declaration in the top so that it could be abbreviated.
from mongoose.
#6268 You can call the .toJson()
method on the retrieved document to get the transformed data
from mongoose.
Why is the Decimal128 being read as an object? shouldn't Mongoose be set up in a way where you don't have to do extra steps to read in an approved data type? Because JavaScript doesn't support decimal arithmetic numbers natively, so we need an object wrapper for that.
The reason why you're getting the new Decimal()
output is because your getter is returning a Decimal128 instance, not a number. If you want to transform the data that Mongoose loads from MongoDB into a different type, a getter is the place to do that, you shouldn't use the getter to just transform into a Decimal128. Try the following instead:
const { Types, model, Schema } = require('mongoose');
const InfoSchema = new Schema({
id: String,
rev: {
type: Schema.Types.Decimal128,
get: v => v == null ? null : +(+v.toString()).toFixed(4)
},
dateCreated: Number,
}, {'toJSON': {getters: true}});
const Info = model('exInfo', InfoSchema);
const doc = new Info({ rev: '123.456789' });
console.log(doc.toJSON()); // Includes `rev: 123.4568`
from mongoose.
Why is the Decimal128 being read as an object? shouldn't Mongoose be set up in a way where you don't have to do extra steps to read in an approved data type? Because JavaScript doesn't support decimal arithmetic numbers natively, so we need an object wrapper for that.
The reason why you're getting the
new Decimal()
output is because your getter is returning a Decimal128 instance, not a number. If you want to transform the data that Mongoose loads from MongoDB into a different type, a getter is the place to do that, you shouldn't use the getter to just transform into a Decimal128. Try the following instead:const { Types, model, Schema } = require('mongoose'); const InfoSchema = new Schema({ id: String, rev: { type: Schema.Types.Decimal128, get: v => v == null ? null : +(+v.toString()).toFixed(4) }, dateCreated: Number, }, {'toJSON': {getters: true}}); const Info = model('exInfo', InfoSchema); const doc = new Info({ rev: '123.456789' }); console.log(doc.toJSON()); // Includes `rev: 123.4568`
I'm still getting the object in the console.log() when trying to pull it from the database. The other items are put in as Number
creatorDescrip: '',
title: 'test',
description: 'test',
rev: new Decimal128("1.2"),
starRating: 3,
dateCreated: 1708958613180,
dateLastAccessed: 1708958613180
from mongoose.
Related Issues (20)
- Vulnerability issue in nested NPM dependency "IP" HOT 2
- Error `the document must have an _id before saving`, but it saves normally HOT 5
- Followup on Transaction retries corrupt subdocument arrays HOT 1
- Compile error when using the mongoose Boolean as a type in a sub-object in a schema. HOT 7
- query.sort(null) should reset the sort options HOT 8
- Mongoose / mongo omitting part of the document when saved HOT 2
- `InferSchemaType` returns `unknown` value HOT 4
- not getting validation error even i am using validate method in my schema HOT 1
- Mongoose v6 modifies connection options object HOT 4
- Model.insertMany with `lean: true` is very slow compared to native driver
- fix: Cannot run `mongoose.createConnection` under `tsx`/ `esbuild`/ `bun` due to the `nextConnectionId` HOT 4
- Populate with TypeScript not working on Cursor HOT 1
- MongoNetworkTimeoutError crashes nodejs process HOT 4
- Missing Typescript detail on Mongoose-specific `options` for updateOne, updateMany, etc. HOT 3
- Facing issue in Mongo+srv which i passing through github actions secrets
- Convenience Method for Converting Array of Strings to ObjectIDs HOT 3
- Round-tripped document fails validation on unmodified Date field HOT 1
- Docs for overwrite option for mongoose.model(), and overwriteModels for mongoose global
- New Mongoose error suddenly due to MongooseError: Buffering timeout HOT 17
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from mongoose.