How do I grab information from my mongodb? - node.js

I have a schema that's been defined as:
const postSchema = new mongoose.Schema({
url: String,
description: String,
created_date: Date
});
Post = mongoose.model('Post', postSchema)
}
and I have a router that posts and saves it to the database.
router.post('/posts', async function (req, res, next) {
try {
const newPost = new Post({
url: req.body.url,
description: req.body.description,
current_time: req.body.created_date
});
await newPost.save();
res.json('status: success!')
console.log(Post)
console.log(newPost)
} catch (error) {
res.json("status: error! " + error + "could not connect to the database");
}
})
I can see the data in my mongdb and it populates when I enter new data through inputs.
With the code below, the id, url, and description print out when I console log the Post.find();
router.get('/posts', async function (req, res, next) {
let allPosts = await Post.find();
console.log(allPosts)
My question is this, how do I get just the url data out of this? I've tried using:
Post.url
req.query.paramNames
I'm looking through Mongodb documentation but I'm missing something.

Post.find({},{url:1,description:1})
You are doing it wrong. The second parameter should help in selecting the fields you need to find.
This will return an Array. If you are looking for specific document you need to change it to findOne and add the search field on first parameter.

Related

how to get the existing collection in mongodb using mongose- Nodejs

In my mongodb i already had a collection and document
Now, i want to use this collection in my node-js using mongoose. how we do this.
const mongoose = require("mongoose");
const schema = mongoose.Schema;
const adminLogin = new schema({
name: { type: String, required: true },
password: { type: String, required: true }
})
module.exports = mongoose.model("adminDetails", adminLogin)
while doing this it is creating new collection. Unable to use the existing collection.
At first you need to make a GET method Router in your jsFile.
like this
app.get("/mainData", async (req, res) => {
const menuInfo = await Nutrients.find({});
res.json(menuInfo);
});
You can set and use VSCode extension "thunderClient"!
like this
enter image description here
setting your request method and URI endpoint
(when you user GET method to get some data in your case, you don't need to write something in request body)
Then, you can see your data on the 'response part' as an Object Data.
If you want to use your data on Front side on your Project, you can use like this!
(in my case, I used jQuery. )
function menu_show() {
$('#result_list').empty()
$.ajax({
type: 'GET',
url: '/mainData', //you need to write same url with your no3.
data: {},
success: function (response) {
console.log(response)
let rows = response['menus']
for (let i = 0; i < rows.length; i++) {
let menuName = rows[i]['menuName']
console.log(menuName)
}
}
}
This is my answer. Let me know if you've solved it!
the image 1 is the structure in the MongoDB. I want to read the data from that collection, below is the code using and the URL and output in post man.
route.get('/adminLogin', (request, response) => {
const data = adminDetails.find({}, (err, result) => {
if (err) {
console.log(err)
} else {
res.json(result)
}
})
})
http://localhost:5000/admin/adminLogin

Update record based on username given in Request body

I need to update value in Group db Group_name to the value send in Json payload.
Db schema
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
username: String,
Group_name: {
type: String,
default: '',
}
});
mongoose.model('User', UserSchema);
And API request
router.put('/join', async(req, res) => {
try {
const data = await User.updateOne(req.params.username, {
Group_name: req.body.Group_name
});
console.log(data)
res.send({ msg: "Group Updated!!!" })
} catch (err) {
console.error(err.message);
res.sendStatus(400).send('Server Error');
}
});
currently its updating only first record which is incorrect , my requirement is to check for all records based on username given and according to username given in request parameters ,i will update value of Group_name to the value sent in request body.
can anyone help me ?
Modify query condition.
const data = await User.updateOne(
{ username: req.params.username },
{ $set: { Group_name: req.body.Group_name } }
);
First of all, understand the difference between req.body & req.params
req.body means hidden parameters sent in request body like in post or put requests.
req.params means defined paramters in URL. For this, you must have it defined in your route like below
router.put('/join/:username', async (req, res) => {
// ^^^^^^^^ here it is defined, now you can access it like
const username = req.params.username;
//or
const {username} = req.params; // destructuring
}
there is one more thing and that is
req.query means undefined paramters attached to URL with ?/&
If you want to give username without pre defining like /join?username=john then use req.query
router.put('/join', async (req, res) => {
const {username} = req.query;
}
Then you should use updateMany() function instead of updateOne()
try {
const {username} = req.params;
const {Group_name} = req.body;
const data = await User.updateMany(
{username}, // find as many users where username matches
{Group_name} // update group name from body
);
console.log(data);
The consoled data would be like { n: 2, nModified: 2, ...} because the update queries don't return updated documents but status of the query. If you want to get updated record set, you have to query again with find().
// after update
const updatedRecord = await User.find({ username });
console.log(updatedRecord);
::POSTMAN::
Postman has two types of parameters
Params
Body
If you add in Params it will be added in URL /join?username=john#email.com&Group_name=GroupB and you have to access it in code with req.query.username or req.query.Group_name
If you add in Body it will be hidden and can be accessed with req.body.Group_name etc
Hope it helps!

Req.body returns undefined : ExpressJs, NodeJs

Please help me I'm having this error for 5 days.
I'm trying to delete data inside of my array on MongoDB
but my req.body returns undefined even though I have my body-parser. I'm using axios.patch for request.
It works well in my postman but once I sent data that's where the problem occurs.
Here's my axios api call.
export const deleteTask = (id,post) => api.patch(`/main/${id}`, post);
Here's my schema.
const todoSchema = mongoose.Schema({
username: {
type: String,
},
password: {
type: String,
},
task: [String],
time: {
type: Date,
default: Date.now,
}
});
const TodoModels = mongoose.model('TodoModels', todoSchema);
here's my query.
export const deleteTask = async (req,res) => {
const { id } = req.params;
console.log(req.body);
if(!mongoose.Types.ObjectId.isValid(id))
return res.status(404).json(`Invalid ID`);
await TodoModels.findByIdAndUpdate(id,{$pull:{ task: req.body.task }},{
new: true });
}
My req.body has no task and I don't know why. Once I send data it returns undefined but the ID from req.params is not undefined.
Also once I sent the data from client to backend/server req.body returns this { data: '' } the data I sent became the element. I believe it was supposed to be { task: 'data' }
If your deleting a record then why are you using findByIdAndUpdate ; it should be findByIdAndDelete. I have put a sample code you to refer. There are 2ways you can delete a record. You can try them out and see.
Way 1:
router.delete('/:id', [auth, admin, validateObjectId], async(req, res) => {
//check for existing genre
const movieGenre = await Genre.findByIdAndDelete(req.params.id);
if (!movieGenre) {
return res.status(404).send('No such movie genre found with given id.');
}
res.send(movieGenre);
})
Way 2:
router.delete('/:id', [auth, admin, validateObjectId], async(req, res) => {
//second way to delete
let movieGenre = await Genre.findById(req.params.id);
if (!movieGenre) {
return res.status(404).send('No such movie genre found with given id.');
}
await movieGenre.deleteOne();
const index = genres.indexOf(movieGenre);
genres.splice(index, 1);
res.send(movieGenre);
})
Hope the answer helps you in any way.

React-Admin displays data from mongoDB but I cannot Edit

I'm using React Admin for the first time, and my users (coming from mongoDB) are displayed just fine. The problem occurs when I click the "edit" (or "delete") button on a specific user: it says "GET http://localhost:3002/api/users/2a1a3a61-f73b-4a01-b609-ae4bb815f59e 404 (Not Found)"
I use "http://localhost:3002/api/users" to make the GET req to mongoDB: "app.use('/api/users', require('./api/GetUsers'))" and "2a1a3a61-f73b-4a01-b609-ae4bb815f59e" is the id of the user I clicked.
I remember when I first started testing React Admin, that I was using jsonplaceholder.typicode to get data and the edit function was working as well, although, of course, would not persist on refresh.
What am I missing? Is the problem the fact that my api's (http://localhost:3002/api/users) purpose is only getting the data and not post/put also, maybe?
/api/GetUsers
const express = require('express');
const mongoose = require('mongoose');
const ContactUser = require('../DB/ContactUser');
const router = express.Router();
const getUsers = async (req, res) => {
ContactUser.find()
.exec((err, user) => {
if(err){
res.json(err);
} else {
res.setHeader('Access-Control-Expose-Headers', 'Content-Range');
res.setHeader('Content-Range', 'users 0-20/20');
res.json(user);
}
})
};
router.route('/').get(getUsers);
module.exports = router;
/DB/ContactUser
const mongoose = require('mongoose');
const contactUser = new mongoose.Schema({
name: String,
email: String,
message: String,
id: String
});
module.exports = mongoose.model('contactUser', contactUser);
You're missing a second route to retrieve not a list of users, but a single user. It will use the id in the URL to find one user. Something like:
router.get('/:id', function(req, res) {
ContactUser
.findOne({ _id: req.params.id })
.exec((err, user) => err ? res.json(err) : res.json(user));
});

I define nested schema , when i fill the inputs it returns nothing and not save in Mongodb

I define nested schema but when I send input data returns nothing,
how can I solve this issue ?
this is my result:
{
"message": "handeling post request to /user-api",
"CreatedUserInfo": {
"_id": "5cbb7fbaad28fe209099a57c"
}
}
this is my code :
const userEduSchema = new mongoose.Schema(
{
eduLevel : String ,
eduField : String,
eduInst :String,
eduCity :String,
eduDate :Date,
proposalTitle :String
}
)
const allEduSchema = new mongoose.Schema(
{
bsc: userEduSchema,
master: userEduSchema,
phd: userEduSchema ,
}
)
module.exports = mongoose.model('Users', allEduSchema )
and it is my user.js for save inpute data in MongoDB I don't know this is true or not:
const userModels = require('../../models/userModels')
router.post('/', (req , res, next) => {
const user = new userModels({
_id : new mongoose.Types.ObjectId,
eduLevel :req.body.eduLevel,
eduField :req.body.eduField,
eduInst :req.body.eduInst,
eduCity :req.body.eduCity,
eduDate :req.body.eduDates,
proposalTitle :req.body.proposalTitle,
})
user.save().then(result =>{
console.log(result)
}).catch (err => {
console.log(err)
})
res.status(201).json ({
message:'handeling post request to /user-api',
CreatedUserInfo : user
})
})```
The problem was in defining the way of get the inputs,I must define the nested object and inside of that put the request bodies as well as I define the nested schema.
bsc:{
bscEduLevel :req.body.bscEduLevel,
bscEduField :req.body.bscEduField,
bscEduInst :req.body.bscEduInst,
bscEduCity :req.body.bscEduCity,
bscEduDate :req.body.bscEduDate,
bscProposalTitle :req.body.bscProposalTitle
}
Have you defined userSchema? If not, you are trying to export a schema which does not exist. Again, in case you have not defined userSchema and you want to export allEduSchema, replace the last line of your model file with this:
const EduSchema = mongoose.model("EduSchema", allEduSchema);
module.exports = EduSchema;
Before you create a new user ,you need to require your "User" moongose Schema. Just like dimitris tseggenes said.
I use async function and try/catch to handle this problem.Maybe you could....
router.post("/", async (request, response) => {
try {
const user = new Users({new user's data here..... });
const result = await user.save();
response.send(result);
} catch (error) {
response.status(400).send(error);
}
});
try catch could avoid some unexpected error and handle it.

Resources