I have a problem to insert a API call with request in mongodb with mongoose. I am very new in this topic. Need your help!!! Here ist my test.js, how can i solve this problem any ideas. My target is to save the Api call from the url and then update it all 30 min but at the moment i was very happy when i could save the call. For all help i am very grateful.
When i start with node test.js then i get only the ids in mongodb not more.
const request = require('request');
const path = require('path');
const https = require('https');
const mongoose = require('mongoose');
const port = 3000;
const dbUrl = process.env.xxx || 'mongodb://localhost:27017/testingDB';
mongoose
.connect(dbUrl, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
.then(() => {
console.log('Connection ready');
})
.catch((err) => {
console.log(err);
});
const app = express();
app.set('views', path.join(__dirname, 'views'));
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
//Create a Schema
const coinSchema = new mongoose.Schema({
id: String,
coin_id: Number,
name: String,
symbol: String,
market_cap_rank: String,
thumb: String,
small: String,
large: String,
slug: String,
price_btc: Number,
score: Number,
});
//Create a Model with collection coins
const Coin = mongoose.model('Coin', coinSchema);
app.get('/testing', async (req, res) => {
const url = 'https://api.coingecko.com/api/v3/search/trending';
request({ url, json: true }, (error, response) => {
if (error) {
console.log(error);
} else {
Coin.insertMany(response.body.coins);
console.log(response.body.coins);
}
});
});
app.listen(port, () => {
console.log(`Server ready on port ${port}`);
});```
Try
request({ url: 'https://api.coingecko.com/api/v3/search/trending', json: true }, function (error, response, body) {
// ...
Coin.insertMany(body.coins.map(({ item }) => item));
});
Related
I am creating a post request that adds new posts to MongoDB. The post request works well and I can see the post in Mongo.
I am struggling at accessing properties from the object using req.body, specifically req.body._id. I would like to console.log the req.body._id to verify that it worked. In the terminal, I keep on getting 'undefined'.
All the solutions I have seen so far say include app.use(express.json()); and app.use(express.urlencoded({ extended: false })); which I have.
I am stumped on what to try next. Any suggestions would be appreciated.
Here is my server.js file
const express = require('express');
const dotenv = require("dotenv").config();
const mongoose = require('./db/mongoose');
const app = express();
const postsRoute = require('./routes/posts');
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use("/posts", postsRoute);
app.listen( process.env.PORT || 5000, (err) => {
console.log(`listening on port ${process.env.PORT}`);
});
Here is my routes file
const express = require('express');
const router = express.Router();
const { allPosts, createPost } = require('../db/models/postModel');
router.get("/", async (req, res) => {
console.log(`req.title is: ${req.title}`);
try {
const posts = await allPosts();
res.send(posts);
} catch (err) {
console.log(err.message);
}
});
router.post("/create", async (req, res) => {
const newPost = req.body;
try {
const addingPost = await createPost(newPost);
console.log(`req.body is:${addingPost}`);
console.log(`req.body title:${addingPost.title}`);
console.log(`addingPost is: ${addingPost} with id of ${addingPost._id}`);
res.send (addingPost);
} catch (err) {
res.status(500).send(err.message);
}
});
module.exports = router;
Here is my Schema file
const mongoose = require('mongoose');
const { Schema } = mongoose;
const postSchema = new Schema({
author: {
type: String,
required: true
},
title: {
type: String,
required: true
},
content: {
type: String,
required: true,
},
tags: [String],
file: String,
likes: {
type: Number,
//We want to default to 0 likes
default: 0,
},
createdAt: {
type: Date,
default: new Date(),
},
});
const postModel = mongoose.model('Post', postSchema);
//Get all posts
const allPosts = async () => {
const posts = await postModel.find();
return posts;
};
//Create posts
const createPost = async (post) => {
const newPost = await postModel.create(post);
return newPost;
};
module.exports = { allPosts, createPost };
Console.log outputs in the Node REPL
I have included a picture showing what the console.log ouputs in the terminal. Hopefully this supports my question.
The problem is when I make the put request using postman there is an error in my vscode terminal that says:
let product = await Product.findById(req.params.id);
^
TypeError: Cannot read property 'id' of undefined.
I am making this request on postman http://localhost:4500/api/v1/product/61dfc2ba3eb817d287929a7a
(61dfc2ba3eb817d287929a7a is the id) with body as raw json. req.params.id is coming to be undefined..
It seemed like an error in parsing so I added body-parser and cors to it but the same error is being showed up..
Code:
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
mongoose
.connect("mongodb://localhost:27017/sampl", {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("db connected");
})
.catch((err) => {
console.log(err);
});
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
const productSchema = new mongoose.Schema({
name: String,
description: String,
price: Number,
});
const Product = new mongoose.model("Product", productSchema);
//create product
app.post("/api/v1/product/new", async (req, res) => {
const product = await Product.create(req.body);
console.log(req.body);
res.status(200).json({
success: true,
product,
});
});
//read product
app.get("/api/v1/products", async (req, res) => {
const products = await Product.find();
res.status(200).json({
success: true,
products,
});
});
//update product
app.put("/api/v1/product/:id", async (res, req) => {
let product = await Product.findById(req.params.id);
product = await Product.findByIdAndUpdate(req.params.id, req.body, {
new: true,
useFindAndModify: false,
runValidators: true,
});
res.status(200).json({
success: true,
product,
});
});
app.listen(4500, () => {
console.log("server is working");
});
The req object represents the HTTP request and has properties for the request query string, parameters, body, and HTTP headers. The res object represents the HTTP response that an Express app sends when it gets an HTTP request.
So, first we want to pass the req object and then res.
change this
app.put("/api/v1/product/:id", async (res, req) => {
let product = await Product.findById(req.params.id);
to
app.put("/api/v1/product/:id", async (req, res) => {
let product = await Product.findById(req.params.id);
I am a beginner nodejs developer, and for a start I decided to develop a blog project for practice. I am using Nodejs Express and native js on the client. When adding a post, nodejs throws an error in the routes:
(node: 25967) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'title' of undefined
at router.post (/routes/post.js:15:25)
Here is my code:
routes/post.js
const express = require('express');
const router = express.Router();
const Post = require('../models/Post');
// http://localhost:5000/api/post (GET)
router.get('/', async (req, res) => {
const posts = await Post.find({})
res.status(200).json(posts)
})
// http://localhost:5000/api/post (POST)
router.post('/', async (req, res) => {
const postData = {
title: req.body.title,
text: req.body.text
}
const post = new Post(postData)
await post.save()
res.status(201).json(post)
})
// http://localhost:5000/api/post/id (DELETE)
router.delete('/:postId', async (req, res) => {
await Post.remove({_id: req.params.PostId})
res.status(200).json({
message: 'Deleted'
})
})
module.exports = router
app.js
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser')
const mongoose = require('mongoose');
const postRouter = require('./routes/post');
const keys = require("./keys");
const port = process.env.PORT || 5000;
const clientPath = path.join(__dirname, 'client');
const app = express();
app.use(express.static(clientPath))
app.use('/api/post', postRouter)
app.use(bodyParser.json())
mongoose.connect(keys.mongoURI, { useNewUrlParser: true,
useUnifiedTopology: true, useCreateIndex: true })
.then(() => console.log('MongoDB connected'))
.catch( err => console.error(err));
app.listen(port, () => {
console.log(`Server has been started on port ${port}`);
});
(model)Post.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const postSchema = new Schema ({
title: {
type: String,
required: true,
},
text: {
type: String,
required: true
},
date : {
type: Date,
default: Date.now
}
})
module.exports = mongoose.model('posts', postSchema)
what could be the problem?
This is an ordering problem, switch these lines around:
app.use('/api/post', postRouter)
app.use(bodyParser.json())
Express middlewere are run in order, which in your case means your post route will be called before the bodyParser middleware is able to parse the JSON body.
I am trying to pass data to a MongoDB collection and it returns Cannot POST /courseweb/course/add
Before passing values through axios I tried postman (a google extension) to send data.
This is my server.js which is implemented with expressjs
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const Bundler = require("parcel-bundler");
const cors = require("cors");
const mongoose = require("mongoose");
const InstructorDB = require('./public/DBModels/InstructorDB');
const router = express.Router();
const bundler = new Bundler("./src/index.html");
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(bundler.middleware());
// app.use(express.static('./src'));
app.use("/courseweb", router);
mongoose.connect("mongodb://127.0.0.1:27017/courseweb", {
useNewUrlParser: true
});
const connection = mongoose.connection;
connection.once("open", () => {
console.log("Connected to MongoDB via 27017");
});
app.listen(3000, err => {
if (err) {
console.error(err);
process.exit(-1);
}
console.log("Application is running on port 3000");
});
app.get("/", function(req, res) {
res.sendFile("./dist/index.html");
});
router.route('/course/add').post((req, res) => {
let instructorDB = new InstructorDB(req.body);
instructorDB.save().then(bookDB => {
res.status(200).send(`${bookDB} Added`);
}).catch((err) => {
res.status(400).send({message: err});
});
});
router.route('/courses').get((req, res) => {
// name of the course database model here
InstructorDB.find().count(function(err, count){
res.status(200).send(count);
});
});
And this is my InstructorDB.js which is a schema model by mongoose
const mongoose= require('mongoose');
const Schema = mongoose.Schema;
let InstructorDB = new Schema({
firstName: String,
lastName: String,
designation: String,
faculty: String,
contactNumber: Number,
email: String,
password: String,
isEnabaled: Boolean,
courses: [{courseID: String}]
});
module.exports = mongoose.model('InstructorDB', InstructorDB, 'InstructorDB');
And this is a screenshot and the response I get when I pass the values through postman. I have set header as content-type and application/json too
Can anyone tell me where I have gone wrong?
Make sure you send the right data via your post request and change the verb to post :
app.post('/course/add', (req, res) => {
if(req.body == null){
return res.status(400).send({message: 'bad request'});
}
let instructorDB = new InstructorDB(req.body);
instructorDB.save((err ,doc ) => {
if(err){
res.status(400).send({message: err});
}
res.status(200).send(`Added`);
});
});
You don't need router if you're going to put it in the same file.
try this syntax instead:
app.post('/coureweb/course/add',((req, res) => {
let instructorDB = new InstructorDB(req.body);
instructorDB.save().then(bookDB => {
res.status(200).send(`${bookDB} Added`);
}).catch((err) => {
res.status(400).send({message: err});
});
}));
then take out
app.use("/courseweb")
I'm trying to build server side back-end code for my website.
I tried app.get request in postman and it worked but when I tried
app.post request in postman it didn't work and gave me errors.
I tried all the solution that was available online and I could understand (I'm Ubuntu user).
Error Screenshot that I get in Postman
The following image will show you the error and format I used in postman
Server.js File (main server file)
const express = require("express");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const app = express();
const mongoose = require("mongoose");
require("dotenv").config();
mongoose.Promise = global.Promise;
mongoose
.connect(process.env.DATABASE, { useNewUrlParser: true })
.then(() => console.log("MongoDB Connected"))
.catch(err => console.log(err));
// // DB config
mongoose.set("useCreateIndex", true);
// const db = require("./config/keys").mongoURI;
// Connect to MongoDB
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
// Models
const { User } = require("./models/user");
//====================================================
// USERS
//====================================================
app.post("/api/users/register", (req, res) => {
const user = new User(req.body);
user.save((err, doc) => {
if (err) return res.json({ success: false, err });
res.status(200).json({ success: true, userdata: doc });
});
});
app.get("/", (req, res) => res.send("hello world"));
const port = process.env.PORT || 3002;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
User Model file (models/user.js)
const mongoose = require("mongoose");
const userSchema = mongoose.Schema({
email: {
type: String,
requrired: true,
trim: true,
unique: 1
},
password: {
type: String,
requrired: true,
minlength: 5
},
name: {
type: String,
requrired: true,
maxlength: 100
},
lastname: {
type: String,
requrired: true,
maxlength: 100
},
cart: {
type: Array,
default: []
},
history: {
type: Array,
default: []
},
role: {
type: Number,
default: 0
},
token: {
type: String
}
});
const User = mongoose.model("User", userSchema);
module.exports = { User };
pass this has a raw data from postman and then call the post api
{
"email": "rohan#getMaxListeners.com",
"password":"pass#123",
"name":"sher",
"lastname":"lock"
}
Postman request should be like below.
{
"email": "rohit***#gmail.com",
"password": "password#123",
"name": "sher",
"lastname": "lock"
}
You are sending an invalid JSON.
Use this JSON for sending Request.
{
"email":"rohan3131313#gmail.com",
"password":"password#123",
"name":"sher",
"lastname:"lock"
}