'How to decrease coins of users in MongoDB?
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?
Solution 1:[1]
- Create
/update-user-balanceendpoint with handler for PUT request - Pass
user_idandamountin the request body - If
user_idoramountare not passed return error findOneAndUpdatewith$incto update balance of the user withuser_idby 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;
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Dharman |
