Reputation: 11
I'm trying to do an API call to my express server to fetch employees that work in the same place based on the location ID. However, the API call returns just an empty array while it does work in the command-line interface.
Employee model
module.exports = mongoose => {
var schema = mongoose.Schema(
{
first_name: String,
last_name: String,
address: {
housenumber: Number,
street: String,
city: String,
zip: Number,
country: String
},
phone: Number,
mobile: Number,
email: String,
enrollment_date: Date,
staff_id: Number,
location: { type : mongoose.Schema.ObjectId, ref : 'location' },
department: String,
function: String,
active: Boolean
},
{ timestamps: true }
);
schema.method("toJSON", function() {
const { __v, _id, ...object } = this.toObject();
object.id = _id;
return object;
});
const Employee = mongoose.model("employee", schema);
return Employee;
};
Employee routing for API
router.get("/location/:location_id", employees.findAllByLocation);
Employee controller handling above call
exports.findAllByLocation = (req, res) => {
Employee.find({ location: req.params.location_id })
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving Employees."
});
});
};
Dummy database data to test on
Postman API call result
However, trying to find the user with that location ID in the command line interface does work and gives the desired output.
[
So somehow it messes up and I can't seem to figure out why it's doing this. I did some research and found that it might have to do with the location being a reference as an ObjectId. So I tried wrapping the req.params.location_id to an ObjectId might fix it but that didn't work.
What's the best way to get this working?
Upvotes: 0
Views: 244
Reputation: 49293
In order to use promise chain, you have to return something and then returned value will be passed chained “then()” as data. In your example you should
return Employee.find({location:req.params.location_id})
Upvotes: 1