I am desperate for some help with an issue I am having updating an item in a mongoDB database. I am creating a simple note application using nodeJS and I have set it up to add notes and remove notes to and from the database with no issues.
When I try to edit notes however, the update does not persist to the database. I dont get an error back and when I console.log the result it displays the correct data but just wont seem to push it to the data base. I have been using mongoose and findByIdAndUpdate. Here is the JavaScript code for my update route
app.put("/:id", (req, res) => {
Note.findByIdAndUpdate(req.params.id, req.body.note, (err, updatedNote) => {
if(err) {
console.log(err);
} else {
res.redirect(`/${req.params.id}`);
console.log(req.params.id);
console.log(req.body.note);
console.log("note updated");
}
});
});
As I mentioned, I dont get any error and the console.logs return the correct id and updated content. All my routes take me to the place so I don't believe there is an issue with them. Any help would be greatly appreciated. I can also provide more code if needed
Thanks in advance
Will
When updating in MongoDB, you have to reference the field you are trying to update. Your code should look like this
app.put("/:id", (req, res) => {
Note.findByIdAndUpdate(req.params.id, {text: req.body.note}, (err, updatedNote) => {
if(err) {
console.log(err);
} else {
res.redirect(`/${req.params.id}`);
console.log(req.params.id);
console.log(req.body.note);
console.log("note updated");
}
});
});
PS: I am hoping the field in the DB model is called text
To make the code look sexier, you can switch it to Async/Await
app.put("/:id", async (req, res) => {
let updatedNote = await Note.findByIdAndUpdate(req.params.id, {text:
req.body.note}, {new: true}).catch(err => console.log(err))
res.redirect(`/${req.params.id}`);
console.log(req.params.id);
console.log(req.body.note);
console.log("note updated");
});
That updatedNote is the same as before the update is expected behavior – see the mongooe docs:
By default, findOneAndUpdate() returns the document as it was before
update was applied. If you set new: true, findOneAndUpdate() will
instead give you the object after update was applied.
This does not mean the update did not take place.
Related
I'm doing a project on an e-commerce website. here I'm with a problem.
I have used the get method to retrieve user data from MongoDB
I have passed the correct parameters and the statement UserId:req.params.userId has been satisfied where we can see in the nodejs terminal.
I'm looking to get only particular user data with UserId === UserId. But in my result, all the user's data is popping up.
Im trying this but the solution im getting is all the users data
i have tried using findOne() but the result is this 635ea7e5e931e12c9f851dd3 user details. where the parameter is 63a8a0f77addf42592eed1e5. where im expecting to get the only user which im passing in parameter.
router.get("/find/:userId", verifyTokenAndAuthorization, async (req, res) => {
try {
const cart = await Cart.find(
{userId : req.params.userId});
console.log("parameter: "+req.params.userId)
return res.status(200).json(cart);
} catch (err) {
res.status(500).json(err);
}
The req.params userId is '63a8a0f77addf42592eed1e5'. i need only this. but it is popping up all the users data.
Node.js terminal showing the parameter is same with userId
Postman showing the response of all users present in the DB but i need only the user details which i had passed in the parameter
Here the mongoDB find method returns all data in the collection, irrespective of the parameters that we pass in to it. Instead try using the findOne method for that collection. So the code with correction will be as follows:
router.get("/find/:userId", verifyTokenAndAuthorization, async (req, res) => {
try {
const cart = await Cart.findOne(
{userId : req.params.userId});
console.log("parameter: "+req.params.userId)
return res.status(200).json(cart);
} catch (err) {
res.status(500).json(err);
}
You can read more about the method at MongoDB Manual.
I had found the solution for my problem i.e I have used filter method at (res(200).json(cart.filter(((user)=>user.UserId === req.params.userId))
This means
Using filter method UserId in my model === to the parameters userId
router.get("/find/:userId", verifyTokenAndAuthorization, async (req, res) => {
try {
const cart = await Cart.find(
{userId : req.params.userId});
console.log("parameter: "+req.params.userId)
res.status(200).json(cart.filter((user)=>user.UserId === req.params.userId));
console.log(cart.filter((user)=>user.UserId === req.params.userId))
} catch (err) {
res.status(500).json(err);
}
});
I'm using TypeScript for making a GET request to get all members whose isCore is true. I've made several entries in the SQL database but it is showing null in res.json. Is the condition syntax is correct?
code:
router.get('/coreMem', async(req, res)=>{
try {
const core_member_details = await Member.findAll({
where:{
isCore: true
}
})
res.status(200).json(core_member_details);
}
catch (err) {
logger.error(`${err}`);
res.status(500).send('Internal Server/Database Error!');
}
});
I think that it, make sure that the Member model is correctly defined and that it is able to connect to the correct table in the database.
if not, a tip for you which is good debugging method:
To return all the records from the members table, you can use the findAll method without any conditions, like this:
router.get('/coreMem', async(req, res)=>{
try {
const all_member_details = await Member.findAll();
res.status(200).json(all_member_details);
},
catch (err) {
logger.error(${err});
res.status(500).send('Internal Server/Database Error!');
}
});
I'm working on making a web app with Electron and I successfully connected to a Mongo DB Atlas database and I'm able to send information to it. However, I seem to be unable to retrieve it. The first snippet of code that I included is how I connected to the database.
MongoClient.connect(URI, (err, client) => {
if (err){
console.log("Something unexpected happened connecting to MongoDB Atlas...");
}
console.log("Connected to MongoDB Atlas...");
currentDatabase = client.db('JukeBox-Jam-DB'); /* currentDatabase contains a Db */
});
Then, this second snippet is how I've been writing to the database, which seems to work perfectly fine.
ipc.on('addUserToDatabase', (event, currentUser) => {
const myOptions = {
type: 'info',
buttons: ['Continue'],
defaultId: 0,
title: 'Success',
message: 'Your account has been created.'
};
dialog.showMessageBox(mainWindow, myOptions);
currentCollection = currentDatabase.collection('UsersInformation');
currentCollection.insertOne(currentUser);
});
Lastly, this is the code that I've been trying to use to retrieve information from the database. I don't see where I could be making a mistake so that it is not working for retrieving, but yes for writing. From my understanding findOne() when passed without parameters should simply return a Promise that resolves to the first entry that matches the query that is passed to it. If a query is not provided then it will resolve to the item that was put in the database first. If there's no entry that matches the query, then it should resolve to null. Any ideas why this isn't working?
ipc.on('checkUsernameRegistration', (event) => {
currentCollection = currentDatabase.collection('UsersInformation');
let myDocument = currentCollection.findOne(); /* I don't understand why this isn't working! */
console.log(myDocument); /* This prints Promise { <pending> } */
if (myDocument !== null){ /* If myDocument is not null, that means that that there is already someone with that username in the DB. */
}
});
Thanks to everyone that is attempting to help me! I've been stuck in this for several hours now.
Try using async/await :
ipc.on('checkUsernameRegistration', async (event) => {
currentCollection = currentDatabase.collection('UsersInformation');
let myDocument = await currentCollection.findOne({ _id: value });
if (myDocument !== null){
console.log(myDocument);
}
});
or, you need to pass a callback, like this:
currentCollection.findOne({ country: 'Croatia' }, function (err, doc) {
if (err) console.error(err);
console.log(doc);
});
This happens because queries are not promises. Actually, I recommend you to study the difference between async and sync code in node.js. Just to understand where the callback should be passed to function, and where you can simply write await Model.method({ options }).
I would like to post multiple objects to my mongo database inside of an express route. Currently, everything is working fine when I do it as a single object (ie ONE casino), please see below, but instead of doing this a million times over, can someone help me do it as one giant data dump so I can post ALL my casinos?
Here is my route that works fine for posting a single object:
router.post('/post', async (req, res) => {
console.log(req.body);
const casinoD = new Casino({
casino: req.body.casino,
table_and_other: req.body.table_and_other,
poker: req.body.poker,
slot_machines: req.body.slot_machines,
total_gaming_win: req.body.total_gaming_win,
year: req.body.year,
month: req.body.month,
combined_date: req.body.combined_date
})
try {
const newCasino = await casinoD.save()
res.status(201).json(newCasino)
} catch (err) {
res.status(400).json({ message: err.message})
}
})
I also understand mongoimport is a better way to do this - however that had its own issues in of itself.
Thanks
Like #JDunken said, you can iterate over the POST body as an array and insert in bulk. You'll want to use
insertMany for speed. To insert millions of records, you will probably want to put a sane limit on the number of records per request, and send API requests in batches. Validation is optional, as Mongoose will run validation according to the schema. It depends on how you want to handle validation errors. Make sure to read up on the ordered and rawResult options for that as well.
router.post('/post', async (req, res) => {
// you should sanity check that req.body is an array first, depending on how robust you want error handling to be
const casinos = req.body.filter(input => isValid(input));
try {
const insertedCasinos = await CasinoModel.insertMany(casinos, { ordered: false });
res.status(201).json(insertedCasinos)
} catch (err) {
res.status(400).json({ message: err.message})
}
})
const isValid(input) {
let valid = true;
// implement input validation
return valid;
}
This is my first attempt at deleting data in a MongoDB database. I'm loosely following this tutorial (just the delete part) to no avail, https://www.airpair.com/javascript/complete-expressjs-nodejs-mongodb-crud-skeleton. I just want to delete all the requested people who are in the requested country. All of my other requests work so I will just post the code that I know is not working, everything else is fine.
EDIT
The error I get in the log is "404 Not Found". When testing w/ Postman the response I get is, "Cannot DELETE /deletepeople/USA/John"
app.delete('deletepeople/:country/:name', function(req, res) {
var countryReq = req.params.country;
var nameReq = req.params.name;
peopleModel
.find({"country":countryReq}, function(err, country) {
country.find({"name": nameReq}, function (err, person) {
person.remove(function (err, person) {
if (err) {
console.log(err);
res.status(500).send();
}
return res.status(200).send();
})
})
})
});
});
country.find({"name": nameReq}, function (err, person) {
The above line is causing you an error, what are you searching in a returned document? Its just an document and not a collection.
You can use the id() method in embedded docs:
Look at the subdocuments [http://mongoosejs.com/docs/subdocs.html]