简体   繁体   中英

Express mongodb find query results empty array

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 commandline 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

Postman API 调用结果

However, trying to find the user with that location ID in the command line interface does work and gives the desired output.

[ Powershell 输出[3]

So somehow it mess 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?

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})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM