1

I faced a strange problem with the mongoose query. when I do db.collection.find() it should be return a object as expected. And I got so in mongo shell

mongo_shell

When I do a similar query in my express router endpoint I got array instead of an object. Like

[
    {
        "dishes": [
            "5eca615117611c0480320c12",
            "5eca615117611c0480320c15"
        ],
        "_id": "5ecae7eb2e746b312cfdf59e",
        "user": "5ec644d06715633270d0414d",
         ...
    }
]

which causes error in my frontend react application. Here is my schema in favorite model:

var favoriteSchema = new Schema(
  {
    dishes: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Dish',
        unique: true,
      },
    ],
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
    },
  },
  {
    timestamps: true,
  }
);

And here is my express endpoint:

.get((req, res, next) => {
    Favorites.find({})
      .then(
        (favorite) => {
          res.statusCode = 200;
          res.setHeader('Content-Type', 'application/json');
          res.json(favorite);
          console.log(favorite);
        },
        (err) => next(err)
      )
      .catch((err) => next(err));
  })

I heartily thank if anyone helps me to figure out this.

0

2 Answers 2

3

You might want to use findOne with mongoose, if you are looking for a single result or null. If you use find you expect more than one row as result.

Bare in mind you should handle the case where "favourite" is null (when you can't find the row you are looking for). At that point you might want to return a different response.

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

Comments

0

.find({parameter}) returns all the objects from database by the given parameter.

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.