Sequelize decimal data save with 2 decimal points - node.js

I'm using sequlize ORM for my Node.js project. Below code is one column in a table.
itemPrice: {
type: DataTypes.DECIMAL,
allowNull: false,
field: 'itemPrice'
},
It is generate the MYSQL DB column as decimal(10,0). It means it cannot save decimal points data. When I'm going to save 12.26, it is save 12. How to create column with saving 2 decimal points.
I tried below code also. It doesn't execute and occurred an error.
itemPrice: {
type: DataTypes.DECIMAL(10,2),
allowNull: false,
field: 'itemPrice'
},
Please show me a direction to do this...

type: DataTypes.DECIMAL(10,2), should work. Once a table is created via sync, it will not be altered even though you have changed your data model definition.
You can use {force: true} in your sync function. Remember that this will drop your table and recreate it.
sequelize.sync({ force: true })
.then(()

Related

One to many relation in Dynamodb Node js (Dynamoose)

I am using Dynamodb with nodejs for my reservation system. And Dynamoose as ORM. I have two tables i.e Table and Reservation. To create relation between them, I have added tableId attribute in Reservation which is of type Model type (of type Table type), as mentioned in the dyanmoose docs. Using the document.populate I am able to get the Table data through the tableId attribute from Reservation table. But how can I retrieve all Reservation for a Table? (Reservation and Table has one to many relation)?
These are my Model:
Table Model:
const tableSchema = new Schema ({
tableId: {
type: String,
required: true,
unique: true,
hashKey: true
},
name: {
type: String,
default: null
},
});
*Reservation Model:*
const reservationSchema = new Schema ({
id: {
type: Number,
required: true,
unique: true,
hashKey: true
},
tableId: table, \\as per doc attribute of Table (Model) type
date: {
type: String
}
});
This is how I retrieve table data from reservation model
reservationModel.scan().exec()
.then(posts => {
return posts.populate({
path: 'tableId',
model: 'Space'
});
})
.then(populatedPosts => {
console.log('pp',populatedPosts);
return {
allData: {
message: "Executedddd succesfully",
data: populatedPosts
}
}
})
Anyone please help to retrieve all Reservation data from Table??
As of v2.8.2, Dynamoose does not support this. Dynamoose is focused on one directional simple relationships. This is partly due to the fact that we discourage use of model.populate. It is important to note that model.populate does another completely separate request to DynamoDB. This increases the latency and decreases the performance of your application.
DynamoDB truly requires a shift in how you think about modeling your data compared to SQL. I recommend watching AWS re:Invent 2019: Data modeling with Amazon DynamoDB (CMY304) for a great explanation of how you can model your data in DynamoDB in a highly efficient manner.
At some point Dynamoose might add support for this, but it's really hard to say if we will.
If you truly want to do this, I'd recommend adding a global index to your tableId property in your reservation schema. Then you can run something like the following:
async function code(id) {
const reservation = await reservationModel.get(id);
const tables = await tableModel.query("tableId").eq(id).exec(); // This will be an array of `table` entries where `"tableId"=id`. Remember, it is required you add an index for this to work.
}
Remember, this will cause multiple calls to DynamoDB and isn't as efficient. I'd highly recommend watching the video I linked above to get more information about how to model your data in an more efficient manner.
Finally, I'd like to point out that your unique: true code does nothing. As seen in the Dynamoose Attribute Settings Documentation, unique is not a valid setting. In your case since you don't have a rangeKey, it's not possible for two items to have the same hashKey, so technically it's already a unique property based on that. However it is important to note that you can overwrite existing items when creating an item. You can set overwrite to false for document.save or Model.create to prevent that behavior and throw an error instead of overwriting your document.

Sequlize generate a table with a foreign key while explicitly requested not to

I have the following association in PersonEntity:
#HasMany(() => SocialPostEntity, {
foreignKey: 'parentId',
foreignKeyConstraint: false,
})
posts?: SocialPostEntity[];
On the other hand the related column on SocialPostEntity:
#Column(DataType.INTEGER)
parentId: number;
The generated create table script has created the parentId column with a foreign key to PersonEntity. event though I have explicitly mentioned foreignKeyConstraint: false
Im not intended to use synchronize: true in production but I'm afraid that it means that my mapping is not accurate.
Bottom line I want parentId to be a simple integer, that's it.
Thanks

How to remove unique option using sequelize

I am using sequelize at nodejs.
When I was making, I set the unique option in a column called 'invoice'.
But since I need to remove the unique option, I have to use migration.
queryInterface.removeConstraint('my_some_table', 'my_constraint');
I saw this command, and I think it is not correct method for me.
How can I remove 'unique option' using migration at sequelize?
invoice: {
type: DataTypes.STRING(50),
unique: true, <<-- I want to remove this.
allowNull: false,
},
This is from the Sequelize documentation and allows you to change the meta data on a column:
queryInterface.changeColumn(
'nameOfAnExistingTable',
'nameOfAnExistingAttribute',
{
type: Sequelize.FLOAT,
allowNull: false,
defaultValue: 0.0
}
)

Execute query in Mongoose schema validation

Im trying to setup my MongoDB design in such a way that there is a projects collection, and a people collection. The Project model schema contains a _people item, which references the People model. (As opposed to the People model having a field to reference the project he/she belongs to. It needs to be like this)
I need to run a validation whenever a new document is created in the people container, that there can be only one manager per a project. This would be very easy if it was possible for me to execute a query for the elements validation in the schema, but I don't believe thats possible...
Heres the schema for the People model currently:
const peopleSchema = new Schema( {
name: {
type: Schema.Types.String,
required: true,
minlength: 3,
maxlength: 25,
trim: true,
select: true
},
isManager: {
type: Schema.Types.Boolean,
default: false,
validate: {
validator: function ( v ) {
// How can I check if there are any existing `people` documents with the
// `isManager` set to true, which are referenced by the same project.
// If I can return a promise from here, then I can just execute a query and verify the results
},
message: 'There can be only one manager per each group'
}
}
})
As you can see in the isManager.validate.validator function, I noted that if this documents isManager is set to true, I need to find a way to check that there isn't already a person document referenced by the same project that is also a manager.
Knowing which project is referencing this document isn't an issue, I will have that somewhere, I just need to know how to run a query.. is that possible?
I was able to accomplish the desired effect by using Mongooses Middleware functionality. Setting up the validation inside the pre-save hook worked just fine

Sails.js & MongoDB: duplicate key error index

I'm using Sails.js (0.9.8) and MongoDB (via the sails-mongo adaptor) to create a collection of pages that can be positioned in a tree-view. I would like to store the path of a page in an array of UUIDs
My model:
module.exports = {
schema: true,
attributes: {
uuid: {
type: 'string',
unique: true,
required: true,
uuidv4: true
},
name: {
type: 'string',
required: true,
empty: false
},
path: {
type: 'array',
required: true,
array: true
}
}
}
It works well when I save a 'root' page (the 'path' property has just one item because it's a root page. Here is what it was saved in MongoDB:
{
_id: ObjectId("52f853e9609fb6c0341bdfcc"),
createdAt: ISODate("2014-02-10T04:22:01.828Z"),
name: "Home Page",
path: [
"a2b23e1f-954b-49a3-91f1-4d62d209a093"
],
updatedAt: ISODate("2014-02-10T04:22:01.833Z"),
uuid: "a2b23e1f-954b-49a3-91f1-4d62d209a093"
}
But when I want to create a 'subpage' below my previous created page (Home Page/Products), I get this error:
MongoError: E11000 duplicate key error index: cms-project.item.$path_1
dup key: { : "a2b23e1f-954b-49a3-91f1-4d62d209a093" }
Here is the data I sent:
{ name: 'Products',
uuid: 'a004ee54-7e42-49bf-976c-9bb93c118038',
path:
[ 'a2b23e1f-954b-49a3-91f1-4d62d209a093',
'a004ee54-7e42-49bf-976c-9bb93c118038' ] }
I probably missed something but I don't know what.
If I store the path in a string instead of an array, it work well, but I find it much less elegant and handy.
Not sure of all the Sails / Waterline parts myself as I've never played with it. But by the error the problem is there is a unique index on your array field.
When you are inserting your second document, you already have one of the values (the parent) in your path field in another document. The unique constraint is not going to allow this. Most certainly for what you are modelling, you do not want this and the index cannot be unique.
I hope that you set this up yourself under the assumption that it meant unique within the array contained in the document. If you did then you know where to look and what to change now. If this is being automatically deployed somehow, then I'm not the one to help.
Change the index to not be unique. You can confirm this through the mongo shell:
use cms-project
db.item.getIndices()
Good luck

Resources