Boris K Boris K - 26 days ago 7
Node.js Question

Mongoose query not returning values

I have a CosmosDB collection called plotCasts, which has objects that look like this:

{
...
"owner" : "winery",
"grower" : "Bill Jones",
...
}


I have the following Mongoose schema:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const plotCastSchema = new Schema({
owner: String,
grower: String,
...
});

const ModelClass = mongoose.model('plotCast', plotCastSchema);

module.exports = ModelClass;


However, when I query the database using the query below, I get an empty array for a result. Any idea why?

PlotCast.find({ owner: 'winery' }).lean().exec(function(err, results) {
if (err) {
res.send(err);
} else if (!results) {
res.send(null);
} else {
res.send(results);
}
});

Answer Source

Okay, you named your model plotCast but your collection is plotCasts.

You can force your collection name this way:

const plotCastSchema = new Schema({
    owner: String,
    grower: String,
    ...
}, { collection: 'plotCasts' });

Or, simply define your Model in mongoose with the collection name as first argument, this way:

const ModelClass = mongoose.model('plotCasts', plotCastSchema);

Please let me know if that's it :)