'Mongoose .find() only works with _id, not with other fields

Document:

[
{_id: 0, symbol: "hi"},
{_id: 1, symbol: "bye"}
]

Code:

const userSchema = new mongoose.Schema({});

const x = mongoose.model('test', userSchema, 'test-org');

app.get('/api/content/:id', (req, res) => {
  x.find({'symbol': 'XXX'})
      .then((result)=> {
      res.send(result);
    });
});

x.find({_id: 0}) and x.find({"_id": 0}) works perfectly fine and returns

{_id: 0, symbol: "hi"}

while: x.find({symbol: "hi"}) and x.find({"symbol": "hi"}) returns whole array of document, not filtering symbol.

{_id: 0, symbol: "hi"}, {_id: 1, symbol: "bye"}

What did i do wrong?

Many Thanks



Solution 1:[1]

Try adding the symbol to the schema definition

const userSchema = new mongoose.Schema({
    symbol: {
        type: mongoose.Schema.Types.String
    }
});

const x = mongoose.model('test', userSchema, 'test-org');

app.get('/api/content/:id', (req, res) => {
  x.find({'symbol': 'XXX'})
      .then((result)=> {
      res.send(result);
    });
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1