Mongoose find returning [object Object], although using lean() and JSON methods

Essentially the title. I am working on the URL Shortener Challenge. I believe everything is working as far as posting, creating, and saving URLs. But when I go to GET the shortened URL, Mongoose returns [object Object]. I read some about trying .lean(), which appears to do nothing (but throws no errors), stringify(did not work) and trying JSON methods (also not working, error says something about converting a circular, then a callback trace).

Relevant code:

const Schema = mongoose.Schema;

var URLSchema = new Schema({
  long: {
    type: String,
    required: true},
  short: {
    type: String,
    required: true}

const NewURL = mongoose.model("NewURL", URLSchema);

// //much later ...

function findURL(shortAPIInput, res, done) {
  //if to check if match and return error if not?
  let returnURL = NewURL.find({short: shortAPIInput}).lean()//.toObject(); //toObject d/n work here n/ a function
  if (returnURL) {console.log("found match in findURL function")};
  console.log("returnURL is "+ returnURL);
  //JSON.stringify - > error
  //return res.rediredct(307, '/adddress/'';)
  //maybe 301?

//get endpoint for getting shortened URL
app.get("/api/shorturl/*", (req, res) => {
  //if/then for proper format of request?
  res.json({greeting: 'getting shortened url'});
  console.log("req url in app.get is " + req.url);
  findURL(req.url, res, done);

[Editable repl link.](

Thanks to anyone who can help!

Mongoose’s Model.find() is asynchronous, so you’ll need callbacks, promises, or async/await to handle that. It’s also the generalist find and will find anything or nothing and not complain. You probably want findOne() or 'findById()` to get one result and then verify it’s the one you want and not null.

The short field probably needs to be some kind of unique identifier type field as well.

Thanks, I thought that might be it. I’m terrible with asynch now, but learning. Also, good point on find() versus other options. I do believe the short identifier is unique because I have a module level variable (not shown in those snippets) that is increased every time a new URL is created in the DB (at least, it increased from 1 to 2 when I tried making multiple POST requests), but I will watch out for that.

Edit: for anyone who finds this question, a modular-level variable might pass the tests but would be reset every time the app runs, so it’s not ideal for longer-term accessibility of the app.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.