mongodb atlas database not accepting POST request - mongodb

I'm currently trying to teach myself REST APIs through following a tutorial and encountering a problem where after trying to send a POST request through Postman, it reaches an error statement. The API accepts the POST json data as it appears in the terminal using console.log(req.body) so I believe its likely a problem with the mongodb connection.
posts.js file:
const express = require('express');
const router = express.Router();
const Post = require('../models/Post');
router.get('/', (req, res) => {
res.send('It works!');
});
router.get('/', async (req, res) => {
try {
const posts = await Post.find();
res.json(posts);
} catch(err){
console.log("Error 2")
res.status(404).json({message:err});
}
});
router.post('/', async (req, res) => {
const post = new Post({
title: req.body.title,
description: req.body.description
});
try {
const savedPost = await post.save()
res.json(savedPost);
} catch (err) {
console.log(req.body)
console.log("Error encountered when attempting to POST")
res.status(404).json({ message: err });
}
});
module.exports = router;
app.js:
const express = require('express');;
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
require('dotenv/config');
const app = express();
app.use(bodyParser.json());
app.use(express.json());
//import the routes
const postsRoute = require('./routes/posts');
//middleware
app.use('/posts', postsRoute);
//Routes
app.get('/', (req,res) => {
res.send('Welcome to the Home Page');
});
//Connect to DB
mongoose.connect(
process.env.DB_CONNECTION,
{useNewUrlParser:true} ,
() => {console.log('Succesfully connected to DB')
});
//Start server listening
console.log('App is running on: http://localhost:3000');
app.listen(3000);
package.json:
{
"name": "api",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon app.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.2",
"dotenv": "^16.0.0",
"express": "^4.17.3",
"mongoose": "^6.2.9",
"nodemon": "^2.0.15"
}
}
Schema file
const mongoose = require('mongoose');
const PostSchema = mongoose.Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('Posts', PostSchema);
console log:
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
App is running on: http://localhost:3000
Succesfully connected to DB
{ title: 'test', description: 'test2' }
Error encountered when attempting to POST

Related

Is there an easier way to post an element in the html-post method?

const express = require("express");
const cors = require("cors");
const dotenv = require("dotenv");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const app = express();
dotenv.config();
app.use(cors());
app.use(bodyParser.json());
const { Schema } = mongoose;
const userSchema = Schema({
imageUrl: { type: String },
description: { type: String },
title: { type: String },
price: { type: Number },
});
const Users = mongoose.model("users", userSchema);
app.get("/", (req, res) => {
res.send("started");
});
`get metod`
app.get("/users", (req, res) => {
Users.find({}, (err, docs) => {
if (!err) {
res.send(docs);
} else {
res.status(404).json({ message: err });
}
});
});
app.get("/users/:id", (req, res) => {
const { id } = req.params;
Users.findById(id, (err, doc) => {
if (!err) {
if (doc) {
res.send(doc);
}
} else {
res.status(404).json({ message: err });
}
});
});
`delete metod`
app.delete("/users/:id", (req, res) => {
const { id } = req.params;
Users.findByIdAndDelete(id, (err, doc) => {
if (!err) {
res.send("Succesfully deleted");
} else {
res.status(404).json({ message: err });
}
});
});
`post metod`
app.post("/users", (req, res) => {
const obj = {
imageUrl: req.body.imageUrl,
description: req.body.description,
title: req.body.title,
price: req.body.price,
};
console.log(obj);
let user = new Users(obj);
user.save();
res.send({ message: " Succesfully added" });
});
const PORT = process.env.PORT;
const url = process.env.URL.replace("<password>", process.env.PASSWORD);
mongoose.set("strictQuery", true);
mongoose.connect(url, (err) => {
if (!err) {
console.log("DB connected");
app.listen(PORT, () => {
console.log("Server start");
});
}
});
I'm trying to learn how exactly get post delete queries work
I'm trying to reduce the code here, but no matter what I do, small errors appear in the end. I have a json string, I want to pass it to POST method. But the 'execute', and 'executeMethod ' are throwing error as below:
"The method execute(HttpUriRequest) in the type HttpClient is not applicable for the arguments (PostMethod)". i have included the depencencies.

API call fails when i put required:true model schema

I am trying to make an api endpoint and this is my model schema MongoDB
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema(
{
username: {
type: String,
required: true,
unique: true,
},
email: {
type: String,
},
password: {
type: String,
},
profilePic: {
type: String,
default: "",
},
},
{ timestamps: true }
);
module.exports = mongoose.model("User", UserSchema);
API logic
const router = require("express").Router();
const User = require("../models/User");
//REGISTER
router.post("/register", async (req, res) => {
try {
const newUser = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password,
});
const user = await newUser.save();
res.status(200).json(user);
} catch (err) {
res.status(500).json(err);
}
});
module.exports = router;
index.js
const express = require("express");
const app = express();
const dotenv = require("dotenv");
const mongoose = require("mongoose");
const authRoute = require("./routes/auth");
const cors = require("cors");
const bodyParser = require("body-parser");
app.use(
bodyParser.urlencoded({
extended: false,
})
);
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
app.use(express.json());
dotenv.config();
mongoose
.connect(process.env.MONGO_URL, {
useUnifiedTopology: true,
useNewUrlParser: true,
})
.then(() => console.log("DB Connected!!!"))
.catch((err) => {
console.log("did not work", err);
});
app.use("/api/auth", authRoute);
app.use("/", (req, res) => {
console.log("main url");
});
app.listen("5002", () => {
console.log("server running");
});
When I am trying to POST call to localhost:5002/api/auth/register , with the following body
{
"username": "testname",
"email": "test#gmail.com",
"password": "122",
}
I get the following error
{
"errors": {
"username": {
"name": "ValidatorError",
"message": "Path `username` is required.",
"properties": {
"message": "Path `username` is required.",
"type": "required",
"path": "username"
},
"kind": "required",
"path": "username"
}
},
"_message": "User validation failed",
"name": "ValidationError",
"message": "User validation failed: username: Path `username` is required."
}
When I remove required:true this api call works but i cant see the fields for username, email, password in collection of the database.
What am I doing wrong here?

Problem setting up node js server to listen for webhook and post to database

Good morning everyone, I'm having a bit of a struggle setting up a server to listen for webhook data and post it to a database. I'm mostly front-end, so some of this is a bit new for me. So I have a deli website that i built on snipcart. I have a receipt printer that queries an api and prints out new orders. So what I'm wanting is a server to listen for the webhook and store the info in a database. I've got it where it listens for the webhook correctly, but it refuses to post to the database. Here's the code in the app.js file.
'use strict';
require('./config/db');
const express = require('express');
const bodyParser = require('body-parser');
const fetch = require('node-fetch');
const app = express();
var routes = require('./api/routes/apiRoutes');
routes(app);
let orderToken;
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.listen(process.env.PORT || 8080);
app.post('/hook', (req, res) => {
orderToken = req.body.content.token;
console.log(orderToken);
const secret = "snipcart api key";
const apiFetch = async function(){
};
let buffered = new Buffer.from(secret);
let base64data = buffered.toString('base64');
const start = async function(){
const request = await fetch('https://app.snipcart.com/api/orders/'+orderToken, {
headers: {
'Authorization': `Basic ${base64data}`,
'Accept': 'application/json'
}
});
const result = await request.json();
console.log(result);
};
start();
res.status(200).end();
});
app.get('/', (req, res) => {
res.send('hello world')
});
Here's the code in my apiController.js file
const mongoose = require('mongoose'),
Order = mongoose.model('apiModel');
// listAllOrders function - To list all orders
exports.listAllOrders = (req, res) => {
api.find({}, (err, api) => {
if (err) {
res.status(500).send(err);
}
res.status(200).json(api);
});
};
// createNewOrder function - To create new Order
exports.createNewOrder = (req, res) => {
let newApi = new api (req.body);
newApi.save((err, api) => {
if (err) {
res.status(500).send(err);
}
res.status(201).json(api);
});
};
// deleteOrder function - To delete order by id
exports.deleteOrder = async ( req, res) => {
await api.deleteOne({ _id:req.params.id }, (err) => {
if (err) {
return res.status(404).send(err);
}
res.status(200).json({ message:"Order successfully deleted"});
});
};
and my apiModel.js file
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ApiSchema = new Schema({
customerName: {
type:String,
required:true
},
customerPhone: {
type:String,
required:true
},
name: {
type:String,
required:true
},
orderNumber: {
type:String,
required:true
},
price: {
type:String,
required:true
},
customFields: {
type:Array,
required:false
},
});
module.exports = mongoose.model("apiModel", ApiSchema);
apiRoutes.js
module.exports = function(app){
var orderList = require('../controllers/apiController');
app
.route('/orders')
.get(orderList.listAllOrders)
.post(orderList.createNewOrder);
app
.route('/order/:id')
.delete(orderList.deleteOrder);
};
and my db.js
const mongoose = require("mongoose");
//Assign MongoDB connection string to Uri and declare options settings
var uri = "<mongodb atlas info>
retryWrites=true&w=majority";
// Declare a variable named option and assign optional settings
const options = {
useNewUrlParser: true,
useUnifiedTopology: true
};
// Connect MongoDB Atlas using mongoose connect method
mongoose.connect(uri, options).then(() => {
console.log("Database connection established!");
},
err => {
{
console.log("Error connecting Database instance due to:", err);
}
});
and here's a sample response that I need to place into the database
{
"token": "93c4604e-35ac-4db7-b3f1-2871476e9e6a",
"creationDate": "2013-10-22T20:54:40.377Z",
"modificationDate": "2013-10-22T20:55:45.617Z",
"status": "Processed",
"paymentMethod": "CreditCard",
"invoiceNumber": "SNIP-1427",
"email": "geeks#snipcart.com",
"cardHolderName": "Geeks Snipcart",
"creditCardLast4Digits": "4242",
"billingAddressName": "Geeks Snipcart",
"billingAddressCompanyName": "Snipcart",
"billingAddressAddress1": "4885 1ere Avenue",
"billingAddressAddress2": null,
"billingAddressCity": "Quebec",
"billingAddressCountry": "CA",
"billingAddressProvince": "QC",
"billingAddressPostalCode": "G1H2T5",
"billingAddressPhone": "1-877-301-4813",
"notes": null,
"shippingAddressName": "Geeks Snipcart",
"shippingAddressCompanyName": "Snipcart",
"shippingAddressAddress1": "4885 1ere Avenue",
"shippingAddressAddress2": null,
"shippingAddressCity": "Quebec",
"shippingAddressCountry": "CA",
"shippingAddressProvince": "QC",
"shippingAddressPostalCode": "G1H2T5",
"shippingAddressPhone": "1-877-301-4813",
"shippingAddressSameAsBilling": true,
"finalGrandTotal": 287.44,
"shippingFees": 10,
"shippingMethod": "Shipping",
"items": [
{
"uniqueId": "1aad3398-1260-419c-9af4-d18e6fe75fbf",
"id": "1",
"name": "Un poster",
"price": 300,
"quantity": 1,
"url": "http://snipcart.com",
"weight": 10,
"description": "Bacon",
"image": "",
"customFieldsJson": "[]",
"stackable": true,
"maxQuantity": null,
"totalPrice": 300,
"totalWeight": 10
},
...
],
"taxes": [
{
"taxName": "TPS",
"taxRate": 0.05,
"amount": 12.5,
"numberForInvoice": ""
},
{
"taxName": "TVQ",
"taxRate": 0.09975,
"amount": 24.94,
"numberForInvoice": ""
},
...
],
"rebateAmount": 0,
"subtotal": 310,
"itemsTotal": 300,
"grandTotal": 347.44,
"totalWeight": 10,
"hasPromocode": true,
"totalRebateRate": 20,
"promocodes": [
{
"code": "PROMO",
"name": "PROMO",
"type": "Rate",
"rate": 20,
},
...
],
"willBePaidLater": false,
"customFields": [
{
"name":"Slug",
"value": "An order"
},
...
],
"paymentTransactionId": null,
}
I dont need all the info placed in the database, just a few key items, like customer name, phone number and the order info. but if there's more than one item in the order, I need it to take that into account and add all the items in the order. here is the docs for the printer that i'm needing to integrate https://star-m.jp/products/s_print/CloudPRNTSDK/Documentation/en/index.html Would appreciate any help that you all can give me. Thanks!
Snipcart will send the webhook to you endpoint for different events. I would suggest you to first filter the event by eventName, because you want to listen for only the order.completed event. After that from the body of the request message, you can extract the items that will be in the req.body.content.items. You can take from the available info what you want and store only that in the database.
Try this:
app.post('/hook', (req, res) => {
if (req.body.eventName === 'order.completed') {
const customer_name = req.body.content.cardHolderName;
const customer_phone req.body.content.billingAddressPhone;
const order_number = req.body.content.invoiceNumber;
let items = [];
req.body.content.items.forEach((item) => {
items.push({
name: item.name,
price: item.price,
quantity: item.quantity,
id: item.uniqueId
});
})
// Now store in database
apiFetch.create({
customerName: customer_name,
customerPhone: customer_phone
name: customer_name,
orderNumber: order_number
customFields: items
}).then(()=>{
res.status(200).json({success:true});
}, (error)=>{
console.log('ERROR: ', error);
})
}
};

Creating a READSTREAM in GFS is throwing an error, does not seem catchable

I am setting up an up/download and have used several resources. I need to be able to store the "files" in the Mongo datastore and then read them back out. I was able to upload, but downloading is through an error when I try to instantiate the createReadStream.
I have over come most of the other errors in the original code. Here is my Package.json:
{
"name": "downloadtest",
"version": "2.3.0",
"license": "MIT",
"scripts": {
},
"engines": {
"node": "6.11.1",
"npm": "3.10.9"
},
"private": true,
"dependencies": {
"body-parser": "^1.19.0",
"core-js": "3.1.3",
"express": "^4.17.1",
"gridfs-stream": "^1.1.1",
"mongoose": "^5.6.7",
"mongoose-unique-validator": "^2.0.3",
"multer": "^1.4.2",
"multer-gridfs-storage": "^3.3.0",
"path": "^0.12.7",
},
"devDependencies": {
}
}
Here is the code that is throwing the error:
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
let mongoose = require('mongoose');
mongoose.connect(mongoURI, { useNewUrlParser: true });
let conn = mongoose.connection;
let multer = require('multer');
let GridFsStorage = require('multer-gridfs-storage');
let Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo;
let gfs = Grid(conn, mongoURI);
let port = 3000;
// Setting up the root route
app.get('/', (req, res) => {
res.send('Welcome to the express server');
});
// Allows cross-origin domains to access this API
app.use((req, res, next) => {
res.append('Access-Control-Allow-Origin' , 'http://localhost:4200');
res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.append("Access-Control-Allow-Headers", "Origin, Accept,Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
res.append('Access-Control-Allow-Credentials', true);
next();
});
// BodyParser middleware
app.use(bodyParser.json());
// Setting up the storage element
let storage = GridFsStorage({
gfs : gfs,
url: mongoURI,
options: {
useNewUrlParser: true
},
filename: (req, file, cb) => {
let date = Date.now();
// The way you want to store your file in database
cb(null, file.fieldname + '-' + date + '.');
},
// Additional Meta-data that you want to store
metadata: function(req, file, cb) {
cb(null, { originalname: file.originalname });
},
root: 'fs', //root name for collection to store files into
curCol: 'fs'
});
// Multer configuration for single file uploads
let upload = multer({
storage: storage
}).single('file');
// Route for file upload
app.post('/upload', (req, res) => {
upload(req,res, (err) => {
if(err){
res.json({error_code:1,err_desc:err});
return;
}
res.json({error_code:0, error_desc: null, file_uploaded: true});
});
});
// Downloading a single file
app.get('/image/:filename', (req, res) => {
console.log('Searching for: '+ req.params.filename);
gfs.collection('fs'); //set collection name to lookup into
/** First check if file exists */
gfs.files.find({filename: req.params.filename}).toArray(function(err, files){
if(!files || files.length === 0){
return res.status(404).json({
responseCode: 1,
responseMessage: "error"
});
}
// create read stream
console.log('Found: ' + files[0].filename)
// console.dir(gfs);
console.dir(files[0])
var readstream = gfs.createReadStream({
filename: files[0].filename,
root: "fs"
});
// // set the proper content type
// res.set('Content-Type', files[0].contentType)
// // Return response
// return readstream.pipe(res);
});
});
app.listen(port, (req, res) => {
console.log("Server started on port: " + port);
});
Finally, here is the error being thrown:
Server started on port: 3000
Searching for: d47e793f3f5492b4e55869d167a471f5_imageThumb.png
Found: d47e793f3f5492b4e55869d167a471f5_imageThumb.png
{ _id:
ObjectID {
_bsontype: 'ObjectID',
id:
Buffer [Uint8Array] [ 90, 104, 195, 29, 197, 30, 94, 0, 20, 99, 208, 206 ] },
filename: 'd47e793f3f5492b4e55869d167a471f5_imageThumb.png',
contentType: 'binary/octet-stream',
length: 13031,
chunkSize: 261120,
uploadDate: 2018-01-24T17:32:14.048Z,
aliases: null,
metadata: null,
md5: '5b314153a6bb0004329ccd1fcf8e037e' }
C:\Users\user\Desktop\downloadtest\node_modules\mongodb\lib\utils.js:132
throw err;
^
TypeError: grid.mongo.ObjectID is not a constructor
I've found a couple of references, but nothing seems to relate. To help troubleshoot, I've put in a couple of console logs and a DIR. I am hitting the DB, I am getting the document.. I just cannot start the read stream.
I found the answer myself, and it was to do with versions and trying to use older models. I found another example that is working. I still need to optimize it.

MongoDB query won't return object in my Express API (React)

I have done this so many times before, but I can't seem to find the issue, it's probably something small and stupid. Take a look at the /server.js file here! (Shortened for demonstration purposes)
/* Make Mongoose promise based */
mongoose.Promise = Promise;
mongoose.connect('mongodb://localhost:27017', options);
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error: '));
/* Routes */
app.route('/games')
.post(postGame)
.get(getGames);
app.route('/games/:id')
.get(getGame)
.delete(deleteGame);
app.route("*").get((req, res) => {
res.sendFile('client/dist/index.html', { root: __dirname });
});
const port = 8080;
app.listen(port, () => {
console.log(`Connected! Server listening on port: ${port}`);
});
Then for my Game model, I have that in app/models/game.js.
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
const gameSchema = new Schema(
{
name: {
type: String,
required:true
},
year: {
type: Number,
required:true
},
description: {
type: String,
required:true
},
picture: {
type: String,
required:true
},
postDate : { type: Date, default: Date.now }
}
);
export default mongoose.model('Game', gameSchema);
This is where I believe I am having the issue.
/* Import Game model schema */
import Game from '../models/game';
const getGames = (req, res) => {
Game.find({}, (err, games) => {
console.log(err, games)
if (err) {
res.send(err);
}
res.json(games);
});
}
const getGame = (req, res) => {
const { id } = req.params;
Game.findById(id, (err, game) => {
if (err) {
res.send(err);
}
res.json(game);
});
}
const postGame = (req, res) => {
let game = Object.assign(new Game(), req.body);
game.save(err => {
if (err) {
res.send(err);
}
res.json({ message: 'Game successfully created!' });
});
};
const deleteGame = (req, res) => {
Game.remove(
{ _id: req.params.id },
err => {
if (err) {
res.send(err);
}
res.json({ message: 'Game successfully deleted!' });
}
);
};
export {
getGames,
getGame,
postGame,
deleteGame
};
Just do be clear... I went into the mongo shell.
I did...
connecting to: test
> db.createCollection('Game')
> db.Game.insert({name: "SSB", year: 2001, description: "Fun Game", picture: "http://google.com", postDate: "2017-01-03T08:51:45.888Z"});
And when I type > db.Game.find({}); I am returned with exactly what I have...
{
"_id" : ObjectId("58c2223e32daa04353e35bdc"),
"name" : "SSB",
"year" : 2001,
"description" : "Fun Game",
"picture" : "http://google.com",
"postDate" : "2017-01-03T08:51:45.888Z"
}
You see when I go to http://localhost:8080/games I am returned with an empty JSON and I just wanna know why. I am 70% sure, it is because it isn't connected to the right collection but I don't remember how to test that :(
I wanted to make this a comment but it won't let me because I don't have a 50 reputation, but I believe I found the issue.
const getGame = (req, res) => {
const { id } = req.params;
Game.findById(id, (err, game) => {
if (err) {
res.send(err);
}
res.json(game);
});
}
In this piece of code you are setting the id to req.params, but you need to set it to req.params.id which is what you passed in your route.
Should look like this:
const {id} = req.params.id;
If you logged id, you would probably get an object that says:
{ id: "[whatever_id_you_put_here]" }
however if you log req.params.id you should get the correct id you put in that spot..
The reason you're getting [] is because you're actually connected to the database and you are actually trying to "get" something, but that something doesn't exist so it sends an empty response.
I hope this helps..