Trouble updating a resource - javascript

I'm trying to update a transaction, but instead its updating that one and at the same time deleting the other ones. My focus is to just update one transaction. Can someone check my backend logic please.
My Schema:
const mongoose = require('mongoose')
mongoose.Schema.Types.String.set('trim', true)
const transactionSchema = mongoose.Schema(
{
note: { type: String, required: true },
amount: { type: Number, default: 0 },
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User',
},
},
{
timestamps: true,
}
)
const WalletSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true,
},
name: {
type: String,
trim: true,
required: [true, 'Please enter a name'],
},
balance: {
type: Number,
default: 0,
},
transactions: [transactionSchema],
createdAt: {
type: Date,
default: Date.now,
},
})
module.exports = mongoose.model('Wallet', WalletSchema)
My backend controller logic:
exports.updateWalletTransactions = asyncHandler(async (req, res, next) => {
const { amount, note } = req.body
const foundWallet = await Wallet.findOne({ user: req.user.id })
foundWallet.transactions = foundWallet.transactions.filter(
(trans) => trans._id.toString() === req.params.id
)
if (foundWallet.transactions) {
foundWallet.transactions[0].amount =
amount || foundWallet.transactions[0].amount
foundWallet.transactions[0].note = note || foundWallet.transactions[0]
const updatedTransaction = await foundWallet.save()
return res.status(200).json(updatedTransaction)
} else {
return next(new ErrorResponse('Transaction not found', 404))
}
})

The problem is that you're using the filter method of Array that will only return the specified transaction.
the better approach is to write your code using the map method like this:
exports.updateWalletTransactions = asyncHandler(async (req, res, next) => {
const { amount, note } = req.body;
const foundWallet = await Wallet.findOne({ user: req.user.id });
if (!foundWallet) return next(new ErrorResponse("no wallet found", 404));
const transIndex = foundWallet.transactions.findIndex(
(trans) => trans._id.toString() === req.params.id
);
if (!transIndex) return next(new ErrorResponse("Transaction not found", 404));
foundWallet.transactions = foundWallet.transactions.map((trans) => {
if (trans._id.toString() === req.params.id) {
trans.amount = amount || trans.amount;
trans.note = note || trans.note;
}
return trans;
});
const updatedWallet = await foundWallet.save();
const updatedTransactions = updatedWallet.transactions;
return res.status(200).json(updatedTransactions);
});
or you can do it like this:
exports.updateWalletTransactions = asyncHandler(async (req, res, next) => {
const { amount, note } = req.body;
const foundWallet = await Wallet.findOne({ user: req.user.id });
if (!foundWallet) return next(new ErrorResponse("no wallet found", 404));
const transIndex = foundWallet.transactions.findIndex(
(trans) => trans._id.toString() === req.params.id
);
const trans = foundWallet.transactions[transIndex];
if (trans) {
trans.amount = amount || trans.amount;
trans.note = note || trans.note;
} else {
return next(new ErrorResponse("Transaction not found", 404));
}
const updatedWallet = await foundWallet.save();
const updatedTransactions = updatedWallet.transactions;
return res.status(200).json(updatedTransactions);
});

You are overwriting the transaction. Better to iterate over each transaction and update on matching transaction id.
exports.updateWalletTransactions = asyncHandler(async(req, res, next) => {
const {
amount,
note
} = req.body;
const foundWallet = await Wallet.findOne({
user: req.user.id
})
let transFound = false;
if (foundWallet) {
foundWallet.transactions.forEach(trans => {
if (trans._id.toString() === req.params.id) {
transFound = true;
trans.amount = amount || trans.amount
trans.note = note || trans.note
}
})
if(transFound){
const updatedTransaction = await foundWallet.save()
return res.status(200).json(updatedTransaction)
} else {
return next(new ErrorResponse('Transaction not found', 404))
}
} else {
return next(new ErrorResponse('User Id not found', 404))
}
})

Related

In a MERN and Axios app, using the mongoose populate function, the field populates in the server/terminal but not on the front end

I am developing a MERN app with axios and trying to populate a field(songList) in a model (User) that is referencing the Schema.Types.ObjectId of another schema (Song).
The _id populates when I create a new Song appropriately.
I can see the entire referenced field is populated in the terminal server side with a console.log but the I cannot get the field to populate on the client side.
My Model; I am trying to populate songList.
const { Schema, model } = require('mongoose')
const bcrypt = require('bcrypt');
const userSchema = new Schema({
username: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
songList: [
{
type: Schema.Types.ObjectId,
ref: 'Song'
}
],
});
userSchema.pre('save', async function (next) {
if (this.isNew || this.isModified('password')) {
const saltRounds = 10;
this.password = await bcrypt.hash(this.password, saltRounds);
}
next();
});
userSchema.methods.isCorrectPassword = async function (password) {
return bcrypt.compare(password, this.password);
};
const User = model("User", userSchema);
module.exports = User;
My server side query, console.log(userSongs) and console.log(user.songList) shows the array of songs appropriately in the terminal:
//login
router.post('/login', async (req, res) => {
const username = req.body.username;
const password = req.body.password;
User.findOne({ username: username })
.populate({path: "songList"})
.exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
if (!user) {
res.status(404).json({ message: 'User Not Found' });
}
const passwordIsValid = bcrypt.compareSync(
password,
user.password
);
if (!passwordIsValid) {
return res.status(401).send({ message: "Invalid Password" });
}
let userSongs = [];
for (let i = 0; i < user.songList.length; i++) {
userSongs.push(user.songList[i])
}
const accessToken = sign(
{ username: user.username, _id: user._id },
"importantsecret");
// res.json({
// token: accessToken,
// username: username,
// _id: user._id,
// songList: user.songList
// });
res.status(200).send({
token: accessToken,
username: username,
_id: user._id,
userSongs: userSongs
});
console.log(userSongs)
});
});
The client side request for the user information where I am hoping to see a populated songList with console.log(singleUser):
const [singleUser, setSingleUser] = useState({})
const [userSongs, setUserSongs] = useState([])
useEffect(() => {
Axios.get(`http://localhost:3001/api/user/${id}`).then((response) => {
setSingleUser(response.data)
})
}, [authState])
Client side login request.
const login = () => {
const data = { username: username, password: password };
Axios
.post("http://localhost:3001/api/user/login", data)
.then((response) => {
if (response.data.error) {
console.log(response.data.error)
} else {
localStorage.setItem('accessToken', response.data.token)
setAuthState({
username: response.data.username,
_id: response.data._id,
status: true
});
window.location.replace('/')
}
})
}
Here is where I create a new Song and add it to the user that is logged in.
router.post('/insert', (req, res) => {
const id = req.body.id;
const songTitle = req.body.songTitle;
const artist = req.body.artist;
const album = req.body.album;
Song.create({ songTitle: songTitle, artist: artist, album: album })
.then((song) => {
return User.findOneAndUpdate(
{ _id: id },
{ $addToSet: { songList: song._id } },
{ new: true }
)
})
.then((user) =>
!user
? res.status(404).json({
message: 'Song created, but found no user with that ID',
})
: res.json('Created the song')
)
.catch((err) => {
console.log(err);
res.status(500).json(err)
})
});
Any suggests on how I can get songList to populate using the populate() mongoose function is much appreciated.
Thank you,
Brandon
I've read articles on stack overflow, 'Mongoose 'populate' not populating",
"Mongoose .populate() not working correctly". Medium articles, and the mongoose documentation.
I've tried sending the user songs in the response back as res.json() and res.send(). The field shows up but is not populated.
I've tried being more specific with songList.songTitle and {path: "songList")
All of these show the field populated in the terminal but not on the front side.

How does a function writer call the getByName . function

books-controllers
I want the data to appear by the name in the postman and not the ID because I have information and I want to fetch it through the name in the database
const getByName = async (req, res, next) => {
const name = req.params.name;
let book;
try {
book = await Book.getByName("name");
} catch (err) {
console.log(err);
}
if (!book)
return res.status(404).json({ message: "No book found" });
}
return res.status(200).json({ book });
};
modelSchema
Here is the Skyma model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bookSchema = new Schema({
name: {
type: String,
require: true
},
description: {
type: String,
require: true
},
price: {
type: Number,
require: true
},
avilable: {
type: Boolean,
},
image: {
type: String,
require: true
},
});
module.exports = mongoose.model("Book", bookSchema);
There in no in-built method in mongoose getByName. You can use generic find to search for object using name
let book = await Book.find({ name: name }).exec();
You can also use findOne if needed.
You can try this -
async function getByName(req, res){
const bookname = req.params.name ;
try {
const book = await Book.findOne({name: bookname})
if(book!==null) {
res.status(200).send({'data': book}) ;
}
else {
res.status(404).send("No book found !")
}
}
catch(error) {
console.log(error)
res.send("Error")
}
}

How can I find a Post of a User?

Hello I want to find posts which user has made ..
I do my request with JWT Token:
###
http://localhost:8080/forum/getByOwnerID
Authorization: Bearer {{token}}
This is my create function :
exports.create = async (req, res) => {
const { forumName, forumDescription } = req.body;
const token = req.token;
const forumExist = await Forum.findOne({ forumName: req.body.forumName });
if(forumExist){
res.status(400).send("Forum Exists already.");
}
try{
const owner = await User.findOne({userID:token._id});
if (!forumName || !forumDescription) {
res.status(400);
throw new Error("Please Fill all the feilds");
return;
}
else {
const newForum = new Forum({ forumName, forumDescription,user: owner.userID });
newForum.user = owner;
const createdNote = await newForum.save();
res.status(201).json(createdNote);
}
}catch(err){
res.status(400).send(err);
}
};
This is my function where I want to get the Posts which the user has made :
exports.getByToken = async (req, res, next) => {
const forum = await Forum.findById( {user: req.token._id} );
if (forum) {
res.json(forum);
} else {
res.status(404).json({ message: "Forum not found" });
}
res.json(forum);
}
And this is model which I have for Post:
const forumSchema = ({
forumName: {
type: String,
required: true,
},
forumDescription: {
type: String,
required: true,
},
user: {
type: Schema.Types.ObjectId,
ref: 'user'
},
published_on: {
type: String,
default: moment().format("LLL")
},
});
Everytime I do a request it has this error :
UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "{ user: 'admin' }" (type Object) at path "_id" for model "Forum"
my generate Token :
const generateToken = (_id, userID) => {
console.log('Signing token for ID ', _id,userID);
console.log('Secret key is ', process.env.JWT_KEY);
const token = jwt.sign({ _id,userID}, process.env.JWT_KEY, {
expiresIn: "30d",
});
console.log('Signed token: ', token);
return token;
};
As you are using findById, you should only send the id as argument function.
If you want to search with filter query, use find method

Api call finds already deleted documents

I've two endpoints: one that delete product document and one that retrieve the document.
After I delete the document throught by Id, the GET api call return me already the document even if it's deleted and It's not present on MongoDb.
Response of DELETE call returns { deletedCount: 1 }
Here code of GET product:
exports.getSingleProduct = (req, res, next) => {
let id = req.params.id;
Products.findById(id).populate({ path: 'internalColor' }).then(result => {
if(result && result.visible == true) {
res.status(200).json(result)
} else {
res.status(404).json({
message: 'product_not_found',
id: id
})
}
}).catch(err => {
res.status(404).json({
message: 'error_operation: ' + err,
id: id
})
});
}
Here code of DELETE product:
exports.deleteDefinallySingleProduct = (req, res, next) => {
let id = req.params.id;
console.log(id)
Products.deleteOne({ id: id }).then(result => {
if(result) {
res.status(200).json({
message: 'deleted_product'
});
}
}).catch(err => {
res.status(404).json({
message: 'error_operation: ' + err
})
})
}
Products Model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const options = {
timestamps: true
}
const productSchema = new Schema({
name: {
type: String,
required: true
},
description: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
externalUrl: {
type: String,
required: true
},
imgUrl: {
type: String,
required: true
},
brand: {
type: String,
required: true
},
visible: {
type: Boolean,
required: true
}
}, options);
const Product = mongoose.model('Products', productSchema);
module.exports = Product;
I think the error that you are facing is caused by a typo in your code.
exports.deleteDefinallySingleProduct = (req, res, next) => {
...
Products.deleteOne({ id: id }).then(result => {
if(result) {
// this code will run always
console.log(result) // will show { n: 0, ok: 1, deletedCount: 0 },
// That is, this section of code will run always despite of delete count being 0 or more due to the request to be excecuted successfully.
...
}
The correct implementation is here:
exports.deleteDefinallySingleProduct = (req, res, next) => {
...
Products.deleteOne({ _id: id }).then(result => {
...
}
This is because by default mongooose use _id representing the document id, unless create a custom id in the schema which you didn't do.

Check if ID exist in related mongodb collection with mongoose

I have a "Drinkers" model and a "Sodas" model which is "related" - a drinker can have drunk X amount of sodas.
The route to get the data is this
router.get('/all/:drinkerId', sodasController.getAllSodasFromDrinker)
In my sodasController, is there a way to check if :drinkerId exists in the "Drinkers" collection and if not return an error that the drinker doesn't exist, without having to require the drinkersController in the sodasController.
Right now getAllSodasFromDrinker looks like this
const Sodas = require("../models/sodas.model");
exports.getAllSodasFromDrinker = async (req, res, next) => {
try {
const id = req.params.drinkerId;
if (id.match(/^[0-9a-fA-F]{24}$/)) {
await Sodas.find({ drinker: id }).exec((err, drinkerItem) => {
if (err) {
return next(err);
}
res.json({ data: drinkerItem });
});
} else {
return next("ID is in the wrong format");
}
} catch (error) {
return next(error);
}
};
In that function, I want to check if a user exists with the applied ID.
I want to avoid having to
const Drinkers = require("../models/drinkers.model") in the sodasController
The Drinkers model:
const Schema = mongoose.Schema;
const drinkersSchema = new Schema(
{
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
sodas: {
type: Schema.Types.ObjectId,
ref: "Sodas",
},
},
{ timestamps: true }
);
The Sodas model
const Schema = mongoose.Schema;
const sodaSchema = new Schema(
{
name: {
type: String,
required: true,
},
drinker: {
type: Schema.Types.ObjectId,
ref: "Drinkers",
},
},
{ timestamps: true }
);
I would add a middleware function which validates if the drinkerId exists. If it exists, you can continue to the controller. If not, then you should throw a 404 error.
Your route:
router.get(
'/all/:drinkerId',
drinkerMiddleware.exists,
sodasController.getAllSodasFromDrinker
);
drinkerMiddleware:
exports.exists = async (req, res, next) => {
try {
const drinker await Drinker.find({ drinker: req.params.drinkerId }).exec();
if (!drinker) {
return next("Drinker not found.");
}
return next();
} catch (error) {
return next(error);
}
};

Categories

Resources