简体   繁体   中英

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

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

the problem is naming the db always saves schema in plural form so it should be like below

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

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