1

I am trying to create a Node.js API endpoint to return some values for population of a select control.

I have the following document in a collection called projectStatusValues...

{
  "_id": {
    "$oid": "5cab4b2b38802527df2f7ab2"
  },
  "projectStatusDesc": [
    "Complete",
    "Pre-Start",
    "Active"
  ]
}

And my Mongoose model is defined as...

const projStatusModel = mongoose.model("projectStatusValues", {
    "projectStatusDesc": [
        String
    ]
});

The finally, I'm using this code to retrieve the array values...

app.get('/v1/projStatus', async (request, response) => {
    try {
        var status = await projStatusModel.find().exec();
        response.send(status);
    } catch (error) {
        response.status(500).send(error);
    }
});

The endpoint looks good and I get a 200 response but an empty string is returned. Any ideas?

Thanks!

3
  • You're not specifying a project ID by the way. Put a console log on status. It doesn't make sense it would return a string, find does not return strings. Commented Apr 8, 2019 at 13:34
  • Thanks for your comment. I don't need to return a project ID here. What does find return? I'm expecting JSON which is a string right? Commented Apr 8, 2019 at 13:46
  • Find will return an array, with all found documents as javascript objects Commented Apr 8, 2019 at 14:00

2 Answers 2

1

You are missing Schema

const Schema = mongoose.Schema;
const projStatusModel = mongoose.model("projectStatusValues", new Schema ({
    "projectStatusDesc": [
        String
    ]
}));

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for that. Tried it but still returns and empty string. I have other API's that seem to work fine without defining a schema, just using model only as with my example. Should I always be defining the schema? What is the consequence of not defining it given that my other API's all work OK without?
I didn't know that it would work without the schema, but since the documentation uses Schema every time, I would suggest to do the same. I noticed you named the model projectStatusValues, and use in your controller as projStatusModel. Is that on purpose?
projectStatusValues is the name of the collection
I'm naming the model projStatusModel when defining as a constant and when using in the controller.
0

Renamed the collection from projectStatusValues to projectstatusvalues and this worked.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.