猫鼬:通过布尔值过滤时,Model.find()返回一个空数组

时间:2019-12-24 20:51:43

标签: node.js mongodb mongoose

我在我的应用程序(带有express的node.js)中定义了以下架构:

const ArtistSchema = new mongoose.Schema({
    name: {type: String, required: true},
    year: {type: Number, required: true},
    genres: {type: [String], required: true},
    imageUrl: {type: String, required: false},
    trending: {type: Boolean, required: false, default: false},
    trendingDate: {type: Date, required: false}
});

以及应该检索那些将trending设置为true的条目的路由:

// GET trending
router.get('/trending', (req, res) => {
    artist.Artist.find({trending: true}).exec((err, trendingArtists) => {
        if (err) {
            console.error(err);
            res.status(500).json({message: err.message});
            return;
        }
        res.json(trendingArtists);
    });
});

但是,即使我的收藏夹中有将trending设置为trending的项目,当我尝试按true字段进行过滤时,它总是返回一个空数组。我尝试将所有内容都用单引号和双引号引起来,并使用1而不是true,但是没有查询返回结果。通过其他字段进行过滤可以很好地工作,根本不进行过滤将返回所有预期的条目。

mongo shell中的条目如下所示:

> db.artists.find({},{name:1,trending:1}).pretty()
{
    "_id" : ObjectId("5de942074a486e2c21246fb9"),
    "name" : "Unwound",
    "trending" : "true"
}
{
    "_id" : ObjectId("5de942074a486e2c21246fba"),
    "name" : "Ladytron",
    "trending" : "true"
}
{
    "_id" : ObjectId("5de942074a486e2c21246fbb"),
    "name" : "Depeche Mode",
    "trending" : "true"
}

console.log在应用程序中生成结果会产生以下结果:

[
  {
    genres: [ 'post-hardcore', 'noise rock', 'indie rock' ],
    trending: true,
    _id: 5de942074a486e2c21246fb9,
    name: 'Unwound',
    year: 1991,
    imageUrl: '2a7f00a1f8e0ab37c647600f6abff67e.jpg',
    trendingDate: 2019-12-20T18:48:53.000Z
  },
  {
    genres: [ 'synthpop', 'electroclash', 'dream pop' ],
    trending: true,
    _id: 5de942074a486e2c21246fba,
    name: 'Ladytron',
    year: 1999,
    imageUrl: 'f26cc1ae1fef371793622bd199b4bb52.jpg',
    trendingDate: 2019-12-20T18:49:05.000Z
  },
  {
    genres: [ 'synthpop', 'new wave' ],
    trending: true,
    _id: 5de942074a486e2c21246fbb,
    name: 'Depeche Mode',
    year: 1980,
    imageUrl: 'e5328919dac971af86dd034781a2da71.jpg',
    trendingDate: 2019-12-20T18:49:43.000Z
  }
]

我正处于智慧的尽头。不管我指定为哪个值,都可能导致通过布尔字段过滤来中断查询(我尝试过true'true'"true"1,{{ 1}},以及虚假的同行?

编辑:由于以下原因,我尝试了一些操作:

1)执行查询后过滤结果可以很好地工作(即只写'1'),尽管显然这不是我想处理过滤查询的方式

2)我要查询的集合是手动创建和编辑的,而不是通过我的应用程序实现的api创建和编辑的。如果我通过api使用POST请求插入新条目,则只要res.json(trendingArtists.filter(a => a.trending === true));设置为trending

,该条目将由查询返回。

3)使用PATCH请求编辑现有条目,其中我将true设置为trending,然后又返回到false,尽管它弄乱了true字段每次将trendingDate更改为trending

时都设置为当前日期

4)如果查询适用于某个条目,则无论我输入什么作为过滤器的值,只要它对猫鼬是真实的,它都将起作用。 true.find({trending: true})一样好

我想问题是猫鼬根本不承认我手动插入的值是真实的,即使理论上应该将它们强制转换为true。我的问题解决了,我猜呢?我不打算在将来手动插入值,这只是为了测试,插入的那些值可以很容易地修复,但是我认为手动还是通过条目编辑对于猫鼬并不重要.find({trending: '1'})。似乎是个错误-我应该关闭问题并在其github上打开错误报告吗?

0 个答案:

没有答案
相关问题