Store Json object in mongoDb with fetch request - node.js

I have a User model and trying to add education field to mongoDB as json object as follows,
User model
education: {
"school": String,
"years":Number
},
Client
//add Education section
const updateEducation = async (e) => {
e.preventDefault();
await fetch(`http://localhost:5000/api/user/updateEducation`, {
method: "PUT",
headers: { "Content-Type": "application/JSON", token: accessToken },
body: JSON.stringify({ userid: userid, educationSchool: educationSchool,
educationYearText: EducationYear}),
})
.then((res) => res.json())
.then((data) => {
console.log("User education is:", data.education +""+data.educationYear);
});
};
Server
const updateEducation = async (req, res) => {
try {
const user = await User.findOneAndUpdate(
{ _id: req.body.userid },
{
$set: {
'education.school': req.body.educationSchool,
'education.years': req.body.educationYearText,
},
}
);
if (!user) {
res.status(404).json("user not exist");
}
res
.status(200)
.json({
education: user.education.School,
educationYear: user.education.years,
});
} catch (error) {
res.status(500).send({ error: error.message });
}
};
When im hitting this endpoint in postman http://localhost:5000/api/user/updateEducation
{
"userid":"63bbe4df75dca5aac7576e47",
"educationSchool":"Test college",
"educationYearText":"2018"
}
Im getting {
"error": "Plan executor error during findAndModify :: caused by :: Cannot create field 'school' in element {education: []}"
}
Whats wrong?

You should $push into an array:
const user = await User.findOneAndUpdate(
{ _id: req.body.userid },
{
$push: {
education: {
school: req.body.educationSchool,
years: req.body.educationYearText,
}
},
},
{ new: true }
);

Related

Cannot save object of array input data into mongodb

how I update my array data in nested array in node js and mongo db. when i was try to save data then massage was print but data not saved in mongo db, please check schema and back end code explain which sentence to create a problem.
// schema
mainmenu: [
{
arrname: String,
submenuarray: [
{
dishname1: {
type: String,
},
prize1: {
type: Number,
},
dishcategory1: {
type: String,
},
},
],
},
];
// back End
app.patch('/addsubmenu/:id/:mainid', async (req, res) => {
const mainid = req.params.mainid;
console.log(mainid);
const id = req.params.id;
console.log(id);
getschema
.findByIdAndUpdate(
{ _id: mainid, 'submenuarray._id': id },
{
$push: {
submenuarray: {
dishname1: req.body.dishname1,
prize1: req.body.prize1,
dishcategory1: req.body.dishcategory1,
},
},
}
)
.then((data) => {
console.log(data);
res.status(201).json(data);
})
.catch((err) => {
console.log(err);
});
});
The findByIdAndUpdate accept the id as first parameter, try to use findOneAndUpdate.
Also, set the flag { new: true} to return the updated object:
getschema
.findOneAndUpdate(
{ _id: mainid, 'submenuarray._id': id },
{
$push: {
submenuarray: {
dishname1: req.body.dishname1,
prize1: req.body.prize1,
dishcategory1: req.body.dishcategory1,
},
},
},
{ new: true }
)
.then((data) => {
console.log(data);
res.status(201).json(data);
})
.catch((err) => {
console.log(err);
});

Finding items with attribute value match excluding another value in Sequelize

I have this code :
module.exports.MyFunction= async (req, res) => {
let token = req.body.token;
let decoded = jwt_decode(token);
let email = decoded.email;
let data = req.body;
let searchUser = data.user;
try {
let user = await User.findAll({
where: {
[Op.or]: [
{ firstName: searchUser },
{ lastName: searchUser },
{ email: searchUser },
{ publicKey: searchUser },
],
},
attributes: ["firstName", "lastName", "email", "publicKey", "avatar"],
}).then((response) => {
return response;
});
res.json({ user });
} catch (err) {
res.json({ err });
}
};
If I run that code, I get all the users that match with the value passed in searchUser.
What I want to do is to exclude the user object that have a specific email.
For instance, if have multiple users named Michel, I want to get all the users with an email address different of the email variable declared at the top of the function, even if their fisrtName matches.
Problem solved by doing this :
module.exports.MyFunction = async (req, res) => {
let token = req.body.token;
let decoded = jwt_decode(token);
let loggedUserEmail = decoded.email;
let data = req.body;
let searchUser = data.user;
console.log(searchUser);
try {
let user = await User.findAll({
where: {
[Op.or]: [
{
firstName: {
[Op.startsWith]: searchUser,
},
},
{
lastName: {
[Op.startsWith]: searchUser,
},
},
{
email: {
[Op.startsWith]: searchUser,
},
},
{
publicKey: {
[Op.startsWith]: searchUser,
},
},
],
email: {
[Op.ne]: loggedUserEmail,
},
},
attributes: ["firstName", "lastName", "email", "publicKey", "avatar"],
}).then((response) => {
return response;
});
res.json({ user });
} catch (err) {
res.json({ err });
}
};

mongoose findOneAndUpdate gives different user

I was trying to $pull an object inside my cart collections. but after I make a request and sent a specific _id it gives me a different person.
this was the _id I sent from my client side.
{ id: '62a849957410ef5849491b1b' } /// from console.log(req.params);
here's my mongoose query.
export const deleteItem = (req,res) => {
const { id } = req.params;
console.log(id);
try {
if(!mongoose.Types.ObjectId.isValid(id)) return res.status(404).json({ message: 'ID not found' });
ClientModels.findOneAndUpdate(id, {
$pull: {
cart: {
product_identifier: req.body.cart[0].product_identifier
}
}
},{
new: true
}).then(val => console.log(val)).catch(temp => console.log(temp));
} catch (error) {
res.status(404).json(error);
}
}
after the request here's the callback.
{
_id: new ObjectId("62a77ab16210bf1afd8bd0a9"),
fullname: 'Gino Dela Vega',
address: '008 Estrella.st santo cristo',
email: 'gamexgaming1997#gmail.com',
google_id: 'none',
birthday: '1997-12-30',
number: 9922325221,
gender: 'Male',
username: 'ginopogi',
password: '$2b$12$YCc1jclth.ux4diwpt7EXeqYyLOG0bEaF.wvl9hkqNVptY.1Jsuvi',
cart: [],
wishlist: [],
toBeDeliver: [],
Delivered: [],
__v: 0
}
as you guys can see after sending a specific _id to find a user...the callback gives me a different user reason that I can't pull the specific object inside cart. (the object I was trying to pull is on another user)
Probably because findOneAndUpdate expect a filter as first parameter, try to switch to findByIdAndUpdate if you want to filter by a specific _id:
export const deleteItem = (req, res) => {
...
ClientModels.findByIdAndUpdate(
id,
{
$pull: {
cart: {
product_identifier: req.body.cart[0].product_identifier,
},
},
},
{
new: true,
}
)
.then((val) => console.log(val))
.catch((temp) => console.log(temp));
} catch (error) {
res.status(404).json(error);
}
};

How to terminate My function, it is working but never ending

I use the api mangopay for my app. The function to transfered worked but it never end until I refresh my page. I have no error code, the function still working but we can't get the message: 'the money is transfered'
Maybe I forgot something on my function ?
transfertMangoReferent: (req, res) => {
Serveur.findOne(
{ email: req.body.email },
"mangoWallet abonne",
(err, user) => {
if (user.abonne === true) {
api.Transfers.create(
{
AuthorId: req.user.mangoID,
DebitedFunds: {
Currency: "EUR",
Amount: req.body.amount * 100,
},
Fees: {
Currency: "EUR",
Amount: req.body.amount * 100 * 0.15,
},
DebitedWalletId: req.user.mangoWalletReferent,
CreditedWalletId: user.mangoWallet,
Tag: "Versement du pot Commun",
},
(model) => {
(error) => {
if (error) {
res.status(500).json({
message: "An error has occured with MANGO users",
});
}else{
res.json(model)
}
};
}
);
} else {
api.Transfers.create(
{
AuthorId: req.user.mangoID,
DebitedFunds: {
Currency: "EUR",
Amount: req.body.amount * 100,
},
Fees: {
Currency: "EUR",
Amount: req.body.amount * 100 * 0.25,
},
DebitedWalletId: req.user.mangoWalletReferent,
CreditedWalletId: user.mangoWallet,
Tag: "Versement du pot Commun",
},
(model) => {
(error) => {
if (error) {
res.status(500).json({
message: "An error has occured with MANGO users",
});
} else {
res.json(model)
}
};
}
);
}
}
);
},
On my network when i click to my button validate i have just the code 200
I can give you also my fetch in a react js
<Button
className="CollectButton"
type="submit"
onClick={() => {
const headers = new Headers({
"Content-Type": "application/json",
Authorization: "bearer " + localStorage.getItem("token"),
});
const data = {
email: element.serveurMail,
amount: this.state.referent.amount,
};
const options = {
method: "POST",
headers: headers,
body: JSON.stringify(data),
};
fetch("https://back-end.osc-fr1.scalingo.io/serveur/referentTransfert", options)
.then((response) => {
return response;
})
.then(
(data) => {
console.log(data);
},
(error) => {
console.log(error);
}
);
}}
>
Envoyez
</Button>

Is there any way to rename the path while we select the complex object from mongodb using mongoose in nodejs?

I want to rename the path of the fields which are coming from the response.
My Query:
const allLeads = await Lead.find().select({
"basic.mobileNumber": 1
});
res.send({ allLeads });
Response I'm Getting
{
"allLeads": [
{
"_id": "5d9f0e2118d1a445bae077aa",
"basic": {
"mobileNumber": "1223654789"
}
},
{
"_id": "5d9f16a8cba7744902acb422",
"basic": {
"mobileNumber": "1123654789"
}
}
]
}
how I want the response
{
_id: 5d9f0e2118d1a445bae077aa,
mobileNumber: "1223654789"
},
{
_id: 5d9f16a8cba7744902acb422,
mobileNumber: "1123654789"
}
So is there any way yo archive this using mongoose?
I did it like this. Is there any other and better way to do this?
let simpleLeadInfo = [];
await SwatiLead.find()
.select({
_id: 1,
"basic.mobileNumber": 1,
})
.exec((err, data) => {
if (!err) {
for (lead in data) {
const obj = {
id: data[lead]._id,
mobileNumber: data[lead].basic.mobileNumber,
};
simpleLeadInfo = [...simpleLeadInfo, obj];
}
return res.send({ error: false, status: "OK", simpleLeadInfo });
}
});

Resources