Hello i'm building an app to shorten urls using nodejs and mongodb
I want to add a counter to each url added to the data base and how many times it was shortened for example
For now it just shortens the url once and gives me the date of the last time i shortened the url
this is my db.config
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Url = require('../models/url');
const db = "mongodb://localhost:27017/url"
mongoose.createConnection(db, err =>{
if(err){
console.error('Error! ' + err)
} else {
console.log('Connected to mongodb url')
}
});
module.exports = router;
This is the model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const URLSchema = new Schema({
urlCode: String,
longUrl: String,
shortUrl: String,
date: {
type: String,
default: Date.now
}
});
module.exports = mongoose.model('url', URLSchema, 'urls');
and this is the api
const express = require('express');
const router = express.Router();
const validUrl = require('valid-url');
const shortid = require('shortid');
const config = require('config');
const Url = require('../models/url');
router.post('/shorten', async (req, res) => {
const { longUrl } = req.body;
const baseUrl = config.get('baseUrl');
// Check base url
if (!validUrl.isUri(baseUrl)) {
return res.status(401).json('Invalid base url');
}
// Create url code
const urlCode = shortid.generate();
// Check long url
if (validUrl.isUri(longUrl)) {
try {
let url = await Url.findOne({ longUrl });
if (url) {
res.json(url);
} else {
const shortUrl = baseUrl + '/' + urlCode;
url = new Url({
longUrl,
shortUrl,
urlCode,
date: new Date()
});
await url.save();
res.json(url);
}
} catch (err) {
console.error(err);
res.status(500).json('Server error');
}
} else {
res.status(401).json('Invalid long url');
}
});
router.get('/', (req, res) => {
Url.find({},(err, docs) => {
if (!err) { res.send(docs); }
else { console.log('Error in Retriving url :' + JSON.stringify(err, undefined, 2)); }
});
});
module.exports = router;
Updated Model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const URLSchema = new Schema({
urlCode: String,
longUrl: String,
shortUrl: String,
date: {
type: String,
default: Date.now
},
count: {
type: Number,
default: 0
});
module.exports = mongoose.model('url', URLSchema, 'urls');
And, the updated API
const express = require('express');
const router = express.Router();
const validUrl = require('valid-url');
const shortid = require('shortid');
const config = require('config');
const Url = require('../models/url');
router.post('/shorten', async (req, res) => {
const { longUrl } = req.body;
const baseUrl = config.get('baseUrl');
// Check base url
if (!validUrl.isUri(baseUrl)) {
return res.status(401).json('Invalid base url');
}
// Create url code
const urlCode = shortid.generate();
// Check long url
if (validUrl.isUri(longUrl)) {
try {
let url = await Url.findOne({ longUrl });
if (url) {
await Url.updateOne({ longUrl }, { count: url.count + 1 }, { upsert: true })
res.json(url);
} else {
const shortUrl = baseUrl + '/' + urlCode;
url = new Url({
longUrl,
shortUrl,
urlCode,
date: new Date()
});
await url.save();
res.json(url);
}
} catch (err) {
console.error(err);
res.status(500).json('Server error');
}
} else {
res.status(401).json('Invalid long url');
}
});
router.get('/', (req, res) => {
Url.find({},(err, docs) => {
if (!err) { res.send(docs); }
else { console.log('Error in Retriving url :' + JSON.stringify(err, undefined, 2)); }
});
});
module.exports = router;
Related
I have a node application using mongo db and Im trying to send back the MongoServerError if there is an error but i only can console.log it like i did in wsService.js
here are my code:
app.js
const errors = require('./helpers/errorHandler');
const users = require('./controllers/wsController')
app.use(errors.errorHandler)
app.use('/ws', ws)
wsModel.js:
const mongoose = require("mongoose");
const { Schema } = mongoose;
const wsSchema= new Schema({
wsKey1: {
type: String,
required: true,
unique: true,
},
wsKey2: {
type: String,
required: true,
}
});
const WS = mongoose.model("ws", wsSchema);
module.exports = WS;
wsService.js:
const WS = require('../models/wsModel')
const createNewInstance= async (object)=>{
console.log(object)
var newInstance = new WS(object)
newInstance.save( (err, session)=> {
if (err) console.log(err);
console.log(session.wsKey1+ " saved to Open Sessions collection.");
return session
});
return {
"session":newInstance
}
}
module.exports = {
createNewInstance,
};
and my controller.js:
router.post('/createNewInstance', (req, res, next)=>{
wsService.createNewInstance(req.body).then(
(session) =>res.send(session)
).catch(
err => next(err)
)
})
I was using formidable#2.0.1 to upload form that contents image, following a tutorial thou. I got the below.
How to debug this error?
Error: The "path" argument must be of type string or an instance of Buffer or URL. Received undefined
Controller.js
const formidable = require("formidable");
const _ = require("lodash");
const fs = require("fs");
const Project = require("../models/projectModel");
exports.create = (req, res) => {
let form = new formidable.IncomingForm();
form.keepExtensions = true;
form.parse(req, (err, fields, files) => {
if (err) {
return res.status(400).json({
error: "Image could not be uploaded",
});
}
let project = new Project(fields);
if (files.image) {
project.image.data = fs.readFileSync(files.image.path);
project.image.contentType = files.image.type;
}
project.save((err, result) => {
if (err) {
return res.status(400).json({
error: errorHandler(error),
});
}
res.json(result);
});
});
};
projectModel.js
const mongoose = require("mongoose");
const { ObjectId } = mongoose.Schema;
const projectSchema = new mongoose.Schema(
{
title: {
type: String,
trim: true,
require: true,
},
category: {
type: ObjectId,
ref: "Category",
required: true,
},
image: {
data: Buffer,
contentType: String,
},
},
{
timestamps: true,
}
);
module.exports = mongoose.model("Project", projectSchema);
In Controller.js I changed files.image.path to files.image.filepath and also changed files.image.type to files.image.mimetype
Controller.js
const formidable = require("formidable");
const _ = require("lodash");
const fs = require("fs");
const Project = require("../models/projectModel");
exports.create = (req, res) => {
let form = new formidable.IncomingForm();
form.keepExtensions = true;
form.parse(req, (err, fields, files) => {
if (err) {
return res.status(400).json({
error: "Image could not be uploaded",
});
}
let project = new Project(fields);
if (files.image) {
project.image.data = fs.readFileSync(files.image.filepath);
project.image.contentType = files.image.mimetype;
}
project.save((err, result) => {
if (err) {
return res.status(400).json({
error: errorHandler(error),
});
}
res.json(result);
});
});
};
use multer npm its works fine
const express = require('express')
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })
const app = express()
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
console.log(req.file, req.body)
})
i'm new learner in backend node js ... in my code below i created an API for questions and it contains get,post,delete and edit
i wanted to test it using the extension rest client in VS code but when i type Get http://localhost:3000/api in route.rest file to test it,it stucks on waiting
is there a way to know if my API works good and can somebody please help me if i have mistake below?
thanks in advance
//server.js
// #ts-nocheck
const express = require('express');
const morgan = require('morgan');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const jwt = require('jsonwebtoken');
const questionRoutes = require('./routes/subscribers');
const cors = require('cors');
const http = require('http');
// Has to be move but later
const multer = require("multer");
const Question = require('./models/subscriber');
// express app
const app = express();
// Explicitly accessing server
const server = http.createServer(app);
// corsfffffffff
app.use(cors());
dotenv.config();
const dbURI = process.env.MONGO_URL || "mongodb://localhost:27017/YourDB";
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(result => server.listen(process.env.PORT || 3000) )
.catch(err => console.log(err));
// register view engine
app.set('view engine', 'ejs');
app.use(express.json);
// middleware & static files
app.use(express.static('public'));
app.use(express.urlencoded({ extended: true }));
app.use(morgan('dev'));
app.use((req, res, next) => {
res.locals.path = req.path;
next();
});
// routes
// question routes
app.use('/questions' , questionRoutes );
// 404 page
app.use((req, res) => {
res.status(404).render('404', { title: '404' });
});
//questionRoute.js
const express = require('express');
const questionController = require('../controllers/questionCon');
const questionApiController = require('../controllers/questionApiController');
const router = express.Router();
// API Routing
router.get('/api/', questionApiController.get_questions);
router.post('/api/add', questionApiController.create_question);
router.get('/api/:id', questionApiController.get_question);
router.delete('/api/delete/:id', questionApiController.delete_question);
router.put('/api/update/:id', questionApiController.update_question);
// EJS Routing for GUI
router.get('/create', questionController.question_create_get);
router.get('/', questionController.question_index);
router.post('/', questionController.question_create_post);
router.get('/:id', questionController.question_details);
router.delete('/:id', questionController.question_delete);
module.exports = router;
//question.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const questionSchema = new Schema({
questionTitle: {
type: String,
required: true,
},
description: {
type: String,
},
price: {
type: Number,
},
});
const Question = mongoose.model('Question', questionSchema);
module.exports = Question;
//questionAPIcontroller
const Question = require('../models/subscriber');
const validators = require('../validators');
let questionApiController = {
// Get a single question
get_question : async (req , res) => {
const id = req.params.id;
try {
const question = await Question.findById(id,(err, question) => {
if (err) return res.status(400).json({response : err});
res.send("hello")
res.status(200).json({response : question})
console.log("hello")
})
} catch (err) {
res.status(400).json(err);
}
},
// Get all the questions
get_questions: async (req , res) => {
try {
const questions = await Question.find((err, questions) => {
if (err) return res.status(400).json({response : err});
res.status(200).json({response : questions})
})
} catch (err) {
res.status(400).json(err);
}
},
// Create a question
create_question : async (req , res) => {
const {error} = validators.postQuestionValidation(req.body);
if(error) return res.status(400).json({ "response" : error.details[0].message})
try {
const question = await new Question(req.body);
question.save((err, question) => {
if (err) return res.status(400).json({response : err});
res.status(200).json({response : " Question created Successfully"})
});
} catch (err) {
res.status(400).json(err);
}
},
// Delete question
delete_question : async (req , res) => {
const id = req.params.id;
var questionExist = false;
var userId ;
const question = await Question.findById(id).then(result => {
questionExist = true;
userId = result.owner;
}).catch(err => {
questionExist = false;
res.status(400).json({response : err });
});
if(questionExist){
try {
Question.findByIdAndRemove(id ,(err, question) => {
// As always, handle any potential errors:
if (err) return res.json({response : err});
// We'll create a simple object to send back with a message and the id of the document that was removed
// You can really do this however you want, though.
const response = {
message: "Question successfully deleted",
id: question._id
};
return res.status(200).json({response : response });
});
} catch (err) {
res.status(400).json(err);
}
}
else {
return res.status(400).send( { "response" : "A question with that id was not find."});
}
},
// Update question
update_question : async (req , res) => {
const id = req.params.id;
Question.findByIdAndUpdate(id,req.body,
function(err, result) {
if (err) {
res.status(400).json({response : err});
} else {
res.status(200).json({response : "Question Updated"});
console.log(result);
}
})
},
// Get question's questions
}
module.exports = questionApiController
//questionController
const Question = require('../models/subscriber');
const question_index = (req, res) => {
Question.find().sort({ createdAt: -1 })
.then(result => {
res.render('index', { questions: result, title: 'All questions' });
})
.catch(err => {
console.log(err);
});
}
const question_details = (req, res) => {
const id = req.params.id;
Question.findById(id)
.then(result => {
res.render('details', { question: result, title: 'Question Details' });
})
.catch(err => {
console.log(err);
res.render('404', { title: 'Question not found' });
});
}
const question_create_get = (req, res) => {
res.render('create', { title: 'Create a new question' });
}
const question_create_post = (req, res) => {
const question = new Question(req.body);
question.save()
.then(result => {
res.redirect('/questions');
})
.catch(err => {
console.log(err);
});
}
const question_delete = (req, res) => {
const id = req.params.id;
Question.findByIdAndDelete(id)
.then(result => {
res.json({ redirect: '/questions' });
})
.catch(err => {
console.log(err);
});
}
module.exports = {
question_index,
question_details,
question_create_get,
question_create_post,
question_delete
}
change code
app.use(express.json);
to
app.use(express.json());
I'm trying to fetch all records from MongoDB starting with the Alphabet S but every time I try doing so, it returns nothing but []. I'm using the Params tab on Postman to do this.
The code that I have written is below as well as a snip from Postman to make the question more understandable. I'm pretty sure that the API I have written to perform this has something wrong with it.
The Model file
const mongoose = require('mongoose');
const entry = new mongoose.Schema({
name : {
type : String,
},
collegeName : {
type : String,
},
location : {
type : String,
}
});
const enter = mongoose.model("Student", entry);
module.exports = enter;
index.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongo = require('mongodb');
const dataModel = require('./model/model');
const MongoClient = mongo.MongoClient;
const uri = "mongodb+srv://coolhack069:XzC6N7dOyUeQl8M9#cluster0.kz6v9.mongodb.net/assignment?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
app.use(express.json());
app.use(bodyParser.json());
const port = 3001;
app.get('/api/get', (req, res) => {
client.connect(err => {
if(err) {
throw err;
}
const collection = client.db('assignment').collection('data');
const fetchedData = {};
collection.find(fetchedData).toArray(function(err, result) {
res.send(result);
client.close();
});
})
});
app.get('/api/getStudentDetails', (req, res) => { //The API I have written to query through the Database
client.connect(err => {
if(err) {
throw err;
}
const collection = client.db('assignment').collection('data');
const fetchedData = new dataModel({
name : req.params.name
});
collection.find(fetchedData).toArray(function(err, result) {
res.send(result);
client.close();
})
})
});
app.post('/api/add', (req, res) => { //To add Data
const name = req.body.name;
const collegeName = req.body.collegeName;
const location = req.body.location;
client.connect(err => {
if(err) {
throw err;
}
const collection = client.db('assignment').collection('data');
const storeData = new dataModel({
name : name,
collegeName : collegeName,
location : location
});
console.log(storeData);
collection.insertOne(storeData, function(err, result) {
res.json({
result : "Success"
});
console.log(err);
client.close();
});
})
});
app.listen(port, () => {
console.log(`Application running at http://localhost:${port}`)
})
The Screenshot from Postman
Your find condition is not correct:
const fetchedData = new dataModel({ // ???
name : req.params.name
});
collection.find(fetchedData).toArray(function(err, result) {
res.send(result);
client.close();
})
??? - I guest your meaning is const fetchedData = { name: req.params.name}; - Find every document which have name is req.params.name (S - in your case). But there is no document has name is S in your collection, then it returns [].
If you want to find the documents with S as the first character of their name, you can use Regex syntax:
const query = {
name : new RegExp('^' + req.params.name, 'i'), // i - case insensitive, => /^S/i
};
collection.find(query).toArray(function(err, result) {
res.send(result);
client.close();
})
am playing with MongoDb and Mongoose, and I am trying to filter by price range, for example display properties from 0 to any number (10000),
My model is very simple:
const mongoose = require('mongoose');
const PropertySchema = mongoose.Schema({
title: String,
description: String,
price: Number,
town: String
})
module.exports = mongoose.model('Property', PropertySchema);
And route. this what am up to, set price from 0 to any number, I don’t want to hard-code this max value
const express = require('express');
const router = express.Router();
const Property = require('../models/Property');
router.get('/', async (req, res) => {
try {
const properties = await Property.find({ price: { $in: [ 0, 0 ] } });
res.json(properties);
} catch (err) {
res.json({ message: err });
}
});
URL
properties?price=0&10000
Can anybody help me with this? How can I set range of price for properties?
You need to pass both priceMin & priceMax from queryParams & use same in your query
const express = require('express');
const router = express.Router();
const Property = require('../models/Property');
router.get('/', async (req, res) => {
try {
const properties = await Property.find({ price: { $gte:req.query.priceMin, $lte: req.query.priceMax } });
res.json(properties);
} catch (err) {
res.json({ message: err });
}
});
URL
properties?priceMin=0&priceMax=10000
You can do this using $gt and $lt
properties?min=0&max=10000
router.get('/', async (req, res) => {
let min = req.query.min;
let max = req.query.max;
try {
const properties = await Property.find({ price: { $gt : min , $lt : max } });
res.json(properties);
} catch (err) {
res.json({ message: err });
}
});