I got an error from exec() function

Tell us what’s happening:
i got the error from exec() function like this :

MongooseError: Operation urls.findOne() buffering timed out after 10000ms
at Timeout. (/home/runner/boilerplate-project-urlshortener-1/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:184:20)

Your code so far
on repl.it :
https://repl.it/@DanhLe5/boilerplate-project-urlshortener-1#server.js

this is my code:

require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();

const bodyParser = require("body-parser");
const mongoose = require("mongoose");

// Basic Configuration
const port = process.env.PORT || 3000;

app.use(cors());

app.use('/public', express.static(`${process.cwd()}/public`));

app.get('/', function(req, res) {
  res.sendFile(process.cwd() + '/views/index.html');
});

// Your first API endpoint
app.get('/api/hello', function(req, res) {
  res.json({ greeting: 'hello API' });
});

app.listen(port, function() {
  console.log(`Listening on port ${port}`);
});


mongoose.connect(
  process.env.MONGODB_CONNECT,
  {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useFindAndModify: false,
    useCreateIndex: true,
  },
  () => {
    console.log("Connected to mongoDB");
  }
);

let urlSchema = new mongoose.Schema({
  original: { type: String, required: true },
  short: Number,
});

let Url = mongoose.model("Url", urlSchema);
let responseObject = {};

app.post(
  '/api/shorturl/new',
  bodyParser.urlencoded({ extended: false }),
  (request, response) => {
    let inputUrl = request.body["url"];

    responseObject["original_url"] = inputUrl;

    let inputShort = 1;

    Url.findOne({})
      .sort({ short: "desc" })
      .exec((error, result) => {
        // the error appears
        console.log(error)

        if (!error && result != undefined) {
          inputShort = result.short + 1;
        }
        if (!error) {
          Url.findOneAndUpdate(
            { original: inputUrl },
            { original: inputUrl, short: inputShort },
            { new: true, upsert: true },
            (error, savedUrl) => {
              if (!error) {
                responseObject["shorten_url"] = savedUrl.short;
                response.json(responseObject);
              }
            }
          );
        } else {
          console.log("hello");
        }
      });
  }
);

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36.

Challenge: URL Shortener Microservice

Link to the challenge:

Your’re using findOne() without any arguments, so the database doesn’t know what you’re looking for. Add some arguments for it to return the right entry.
I also see that in your repl.it, you changed it to find() which should return the whole database, that’s a lot of data transferred when you don’t need to pull the whole thing to the client side.

also, unrelated notes,:

  • you can write request.body.url instead, since the key url is always the same.
  • look into try/catch for error handling
1 Like

thank you for your reply, there actually no data in the database, for the sake of learning I don’t think that has anything to do with the current error? isn’t it?

It should return an empty json, but you say it times out so something else is wrong. Double check the url. You can also use the app Postman to test your database.