简体   繁体   中英

Mongoose query returning empty array

Below is my express endpoint that returns an empty array

router.get('/myUnits/:landlord_id', wagner.invoke((Apartment) => {
    return (req, res) => {
      Apartment.find({ postedBy: req.params.landlord_id }, (err, apt) => {
        if (err) {
          return res.status(status.INTERNAL_SERVER_ERROR)
                    .json({ error: err.toString() })
        }
        if (!apt) {
          return res.status(status.NOT_FOUND)
                    .json({ error: 'Not found' })
        }
        return res.json(apt)
      })
    }
  }))

I changed Apartment.find({ price: 200 }) and it queries all data with the price: 200 but querying for postedBy does not work at all.

When I go to my mongo shell and do a query

db.apartments.find({ postedBy: 'the id of the account here' })

it returns the appropriate data.

https://gyazo.com/77afa64f9afb75f47667d0f47757c3e4

I figured it out. It was in my schema all along.

let apartmentSchema = {
  name: { type: String, required: true },
  price: { type: Number, required: true },
  promotion: { type: String, required: true },
  postedOn: { type: Date, required: true },
  postedBy: {
    type: mongoose.Schema.Types.ObjectId, // this was the culprit
    required: true
  }
}

I just changed the type to String. I used the ObjectId from a previous api that I long since updated. Thank you for your patience guys!

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