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?
CodePudding user response:
- Create
/update-user-balance
endpoint with handler for PUT request - Pass
user_id
andamount
in the request body - If
user_id
oramount
are not passed return error findOneAndUpdate
with$inc
to update balance of the user withuser_id
by negativeamount
const express = require('express');
const Users = require('../models/user');
const router = express.Router();
router.put('/api/v1/update-user-balance', async (req, res, next) => {
try {
const { user_id, amount } = req.body;
if (!user_id || !amount){
console.log('ERROR: "user_id" and "amount" data are required.';
return res.status(400).json({ success: false });
}
await Users.findOneAndUpdate(
{ _id: user_id },
{ $inc: { coins: amount * -1 },
});
console.log('User balance successfully updated')
return res.status(200).json({ success: true });
} catch (error) {
console.log('ERROR: ', error);
return res.status(400).json({ success: false });
}
});
module.exports = router;
CodePudding user response:
https://mongoosejs.com/docs/documents.html
Refer the above documentation.
You can update documents using queries in mongoose.
Ex:
await model.updateMany({}, { $set: { coins: 10 } });
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.