Hello
I’m having trouble with my URL Shortener Microservice, since Model.find() always returns an empty array regardless of what the query is. I’m feeling kinda lost, all I know is that the connection is happening and the “queries” are being “registered” (the operation status window shows whenever I make a query, it is just always the same empty array). Any help would be tremendously appreciated. Thanks!
//Get requirements and set instances
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const mongo = require("mongodb");
const mongoose = require("mongoose");
const dns = require("dns");
const shortid = require("shortid");
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//Allows node to find static content
app.use("/public", express.static(`${process.cwd()}/public`));
//Listen check
app.listen(process.env.PORT || "7000", () => {
console.log("NodeJS is listening...");
});
//Connection
mongoose.connect(
"mongodb+srv://Iker:whateverpw@cluster0-b7shj.mongodb.net/test?retryWrites=true",
{
useNewUrlParser: true
}
);
const db = mongoose.connection;
db.on("error", console.error.bind(console, "MongoDB connection error"));
db.once("open", () => {
console.log("Connected to db...");
});
const Schema = mongoose.Schema;
const urlSchema = new Schema({
original: { type: String, required: true },
id: String
});
const UrlModel = mongoose.model("UrlModel", urlSchema);
app.get("/", (req, res) => {
res.sendFile(`${process.cwd()}/index.html`);
});
app.post("/api/shorturl/new", (req, res) => {
UrlModel.find({ original: req.body.url }, (err, data) => {
if (err) {
console.log(err);
}
if (data) {
res.json({ data: data });
console.log(data);
} else {
res.json({ original_url: req.body.url });
console.log(`${req.body.url} not found.`);
}
});
/*
const regex = /^https?:\/\/www\./gi;
//const original = req.body.url;
if (regex.test(req.body.url)) {
const original = req.body.url.replace(/^https?:\/\//, "");
//console.log(original.replace(/^https?:\/\//, ""));
}
res.json({ url: req.body.url });
dns.lookup("www.google.com", (err, address) => {
console.log(address);
});
*/
});