I am creating a project with MongoDB Atlas/Cloud and I have the method to obtain ALL the data of a database that I have created from the cloud.
This is how I did it:
router.get('/', (req, res) => {
// http://localhost:3000/data
client.connect(async err => {
if (await err) {
console.log("Error connecting to MongoDB Cloud:\n\t" + err.toString());
}
console.log("Connected to the DB!");
const collectionData = client.db("myDatabase").collection("data");
try {
const data = await collectionData.find().toArray();
console.log(data);
res.json(data);
} catch (e) {
res.json({message: e});
}
await client.close();
});
});
But I would like to be able to collect each data individually by introducing its _id in the URI. This is how I tried to do it:
router.get('/:dataID', (req, res) => {
// http://localhost:3000/data/<ID>
client.connect(async err => {
if (await err) {
console.log("Error connecting to MongoDB Cloud:\n\t" + err.toString());
}
console.log("Connected to the DB!");
const collectionData = client.db("myDatabase").collection("data");
try {
console.log(req.params.dataID); // It works, it prints the _id
const specificData = await collectionData.findById(req.params.dataID).toArray();
console.log(specificData);
res.json(specificData);
} catch (e) {
res.json({message: e});
}
await client.close();
});
});
But it doesn't work. I'm retrieving a blank object: message: {}. I've checked the _id introduced, it's exactly the same as the _id from the mongoDB object that I'm trying to retrieve. What am I doing wrong? It should be the const specificData = await collectionData.findById(req.params.dataID).toArray(); but I don't know what to change to make it work right.
P.S.: After making a GET petition to the server to /data, I get the data, but if I try to make another petition after that, I get an MongoDB Error, do anyone know why is this happening? Thank you in advance
Solved:
const specificData = await collectionData.find(req.params.dataID).toArray();
console.log(specificData.get[0]);
Related
This is my node JS
const router = require("express").Router();
const Posts = require("../../models/vendorProjectsDatabaseExcellUpload");
router.post('/vendorProjectsDatabasesExcell/save',(req,res) => {
const newPost = req.body;
// console.log(newPost);
// Posts.insertMany(newPost).then((err) =>{
// if(err){
// return res.status(400).json({
// error:err
// });
// }
// return res.status(200).json({
// success:"Project Details Added Successfully"
// });
// });
try {
const options = { ordered: true };
const result = Posts.insertMany(newPost, options).then((err) =>{
if(err){
return res.status(400).json({
error:err
});
}
return res.status(200).json({
success:"Project Details Added Successfully"
});
});
console.log(`All documents were inserted`);
} finally {
console.log('done');
}
});
module.exports = router;
This is my React.js
const uplaodHandler = async (e) => {
// const uplaodHandler = (e) => {
e.preventDefault();
const newPost = items;
// console.log(newPost);
await axios
.post('http://localhost:8072/vendorProjectsDatabasesExcell/save', newPost)
.then((result) => {
alert(result);
alert('New Project Added now');
// navigate('/dashboard/DatabasesUploadProjectFilesVendorProjects', { replace: true });
console.log(newPost);
})
.catch((error) => {
console.log(error);
// console.log(error.response.data);
// console.log(error.response.status);
// console.log(error.response.headers);
});
};
Other post and put request in other pages of the same app is works fine without any error.
In here also the json data array post to the mongo DB without any issue. Only problem is it is giving the bad request 400 error.
Just modify this part:
const result = Posts.insertMany(newPost, options)
.then((res) =>{
return json({success:"Project Details Added Successfully"});
}).catch((err) => {
return json({error:err});
});
I have the following express code. If I try to get a document with a non-existent id, I get nothing. The problem is that I get 200 as response status and I don't get the Failed message. The code jumps every time into "then".
const Mymodel = require('../model/Mymodel');
const Single = (req, res) => {
const id = req.params.id;
Mymodel.findById(id)
.then(result => {
res.send(result);
})
.catch(err => {
console.log(err);
res.status(404).send({"Failed": "Document not found"});
});
}
your finding query response is null so this is not an error. if you send res.status(404).send({"Failed": "Document not found"}); response for not found use this.
const Mymodel = require('../model/Mymodel');
const Single = (req, res) => {
const id = req.params.id;
Mymodel.findById(id)
.then(result => {
if(result){
res.send(result);
}else{
res.status(404).send({"Failed": "Document not found"});
}
})
.catch(err => {
console.log(err);
res.status(404).send({"Failed": "Document not found"});
});
}
This is my code;
I'm try for update user data. like so you are seen this code. But result coming null.
I'm not understand. please help me guys
// #Router UPDATE /updateforslip/:id
// #desc UPDATE update by ID
// #access Private
router.put('/update/user/data/:id', async (req, res) => {
var update = Pan.findByIdAndUpdate(req.params.id, {
$set: req.body
})
console.log(update)
update.exec((error, data) => {
if (error) throw error;
res.json(data)
})
})
Coming result
in console.log(update)
null
I'm using postman for request.
try this:
router.put('/update/user/data/:id', async (req, res) => {
tyr{
var update = await Pan.findByIdAndUpdate(req.params.id, {$set: req.body})
res.json(update)
}catch (err){
throw error;
}
Just try like this, don’t use exec() when you want to uae async await
and use try/carch for handling errors
try{
var data = await Pan.findByIdAndUpdate(req.params.id, {
$set: req.body
}).lean();
res.json(data)
},
catch(error){
}
I am trying to read data from an html form through a POST, store it in a mongoDB and query it using model.find() and print it in console. But when i run this for the first time the find() is returning an empty object and on giving the next input the previous data excluding the current input is retrieved by th find(). How can i print the full collection including the freshly entered data
app.post("/", function(req, res){
postTitle = req.body.postTitle;
postDesc = req.body.postDesc;
const post = new Post({
title:postTitle,
desc:postDesc
});
post.save();
Post.find({}, function(err, data){
if(err){
console.log(err);
}else{
console.log(data);
}
});
//console.log(postTitle, postDesc);
});
The command post.save(); will just begin working and your code will continue meanwhile. When your Post.find({} ... starts working, your post.save(); haven't finished working, and thus you're not getting the results.
Change the function so you wait for the save to give you a callback with an ok and then you can query the database.
app.post("/", function(req, res) {
const postTitle = req.body.postTitle;
const postDesc = req.body.postDesc;
const post = new Post({
title: postTitle,
desc: postDesc
});
post.save(function(err) {
if (err) {
// Something went wrong with the save, log and return the error message
console.error(err);
return res.send(err);
}
console.log(`Post "${postTitle}" saved to database.`);
// Since we know that the post has been saved, continue querying the database.
Post.find({}, function(err, data) {
if (err) {
// Something went wrong with the query, log and return the error message
console.error(err);
return res.send(err);
}
console.log(data);
res.send(data);
});
});
});
This code is not tested.
You can also try async/await out, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function and also mongoose documentation for promises & async/await https://mongoosejs.com/docs/promises.html.
I myself would write the function like this using async/await and es6.
app.post('/', async(req, res) => {
const post = new Post({
title: req.body.postTitle,
desc: req.body.postDesc
});
try {
await post.save();
const posts = await Post.find();
console.log(posts);
} catch (err) {
console.error(err);
}
res.end();
});
You can try with exec
Post.find({}).exec(function (err, d) {
if(err){
console.log(err);
}else{
console.log(d);
}
});
Or try to use async await to make sure your query is running step by step
const user_info = await Post.find({});
This code is not tested
here post.save() is an async function that means it does not complete immediately. You need to use async - await in order to wait for the save() function to finish and then you query the database.
I am using Nodejs and cloud firestore as a database, i got the right data from database (logout) in model but after returning it back to controller i can not got it
// this is controller:
CheckPhoneNumber = (req, res) => {
// getting data from json
var json = {
// this is the entry ==> PhoneNumber : 123456789
PhoneNumber: req.body.PhoneNumber
}
// calling model function
console.log('this is from controller before calling database');
var user = model.CheckPhoneNumber(json.PhoneNumber)
.then(function () {
console.log('this is from controller after calling database');
console.log(user);
return user;
}).catch(err => {
return 'Error in controller awaiting ', err;
});
// outputting to Postman
return res.json(Promise.resolve(user));
}
and that controller calls the below model
// this is model :
// importing configure of database
const config = require('../config/main');
// this is for updates from google to firestore
config.db.settings({ timestampsInSnapshots: true });
// setting root of users database
const usersRoot = config.db.collection( my root here );
// takes json and return that user which phone number belongs to (actually it gets user by phone number )
async function CheckPhoneNumber(PhoneNumber) {
// getting data from database
var user;
user = await usersRoot.where('PhoneNumber', '==', PhoneNumber).get()
.then(async snapshot => {
if (snapshot.empty) {
return 'No matching documents.';
}
return await snapshot.forEach(async doc => {
console.log('your user is : ');
user = await doc.data();
console.log(user);
console.log('this is from model after calling database');
return await user;
});
}).catch(err => {
// console.log('Error getting documents',err);
return 'Error getting documents', err;
});
console.log('this is user befor returning : ');
console.log(user);
return user;
}
and this is the output of console in windows OS
this is from controller before calling database
this is from model after calling database
{ ... there is here some data ... }
this is from controller after calling database
Promise { <'pending'> }
I expect to get the data i returned from controller speicially after i await it to get data from database in the last line of console
It's because your user is a promise object.
You may want to respond in this block like,
model.CheckPhoneNumber(json.PhoneNumber)
.then(function (user) {
console.log('this is from controller after calling database');
console.log(user);
res.json(user)
})
.catch(err => {
res.json('error')
});
Or, you do it this way:
// make you route function async
CheckPhoneNumber = async (req, res) => {
...
// then you could
try {
const user = await model.CheckPhoneNumber(json.PhoneNumber)
res.json(user)
} catch (e) {
res.json('error')
}
change your model to:
async function CheckPhoneNumber(PhoneNumber) {
// getting data from database
try {
var snapshot = await usersRoot.where('PhoneNumber', '==', PhoneNumber).get()
if (snapshot.empty)
return "No"
var datas = [];
snapshot.forEach(doc => {
datas.push(doc.data())
})
return datas;
} catch (e) {
console.error(e);
}
}