I am a building a web-app where people have 10 coins by default, and when they click a buy button, it reduces the number of coins by 10 with each click.
The schema for users is like this:
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema(
{
username: {
type: String,
require: true,
min: 3,
max: 20,
unique: true,
},
email: {
type: String,
required: true,
max: 50,
unique: true,
},
password: {
type: String,
required: true,
min: 6,
},
isAdmin: {
type: Boolean,
default: false,
},
coins: {
type: Number,
default: 10,
},
},
{ timestamps: true }
);
module.exports=mongoose.model("User", UserSchema);
How do I write a code to use a button to reduce the number of coins?
2
Answers
https://mongoosejs.com/docs/documents.html
Refer the above documentation.
You can update documents using queries in mongoose.
Ex:
You can set the value of coins parameter in query and update.
Before updating the document, you need to take the document using model.findOne fuction and get the available coins of the user.
After that you need to do -10 calculation and update the document.
/update-user-balance
endpoint with handler for PUT requestuser_id
andamount
in the request bodyuser_id
oramount
are not passed return errorfindOneAndUpdate
with$inc
to update balance of the user withuser_id
by negativeamount