Mongodb [ObjectId]中的Mongoose$返回0条记录

Mongodb [ObjectId]中的Mongoose$返回0条记录,mongodb,mongoose,objectid,Mongodb,Mongoose,Objectid,在我们的猫鼬模型中,有一个产品引用了一篇文章 这是模式的一部分: const product = new Schema({ article_id: Schema.Types.ObjectId, title: String, description: String, ... 在API中,我们正在寻找引用特定文章列表的产品,我想使用$In操作符: const articles = ["5dcd2a95d7e2999332441825", "5d

在我们的猫鼬模型中,有一个产品引用了一篇文章

这是模式的一部分:

const product = new Schema({
  article_id: Schema.Types.ObjectId,
  title: String,
  description: String,
...
在API中,我们正在寻找引用特定文章列表的产品,我想使用$In操作符:

const articles = ["5dcd2a95d7e2999332441825", 
                    "5dcd2a95d7e2999332441827", 
                    "5dcd2a96d7e2999332441829"]
filter.article_id = {
  $in: articles.map(
    article => new mongoose.Types.ObjectId(article)
  ),
};

return Product.find({ ...filter })
这将返回0条记录,而我确信它应该至少返回3条记录。查看控制台日志,所发生的一切是在
ObjectId
转换期间从数组中删除了双引号

然后,我尝试了一种不同的方法,为每个映射数组项返回
{$oid:“id goes here”}

const articles = ["5dcd2a95d7e2999332441825", 
                    "5dcd2a95d7e2999332441827", 
                    "5dcd2a96d7e2999332441829"]
filter.article_id = {
  $in: articles.map(
    article => ({$oid: article})
  ),
};

return Product.find({ ...filter })
这将提供一个不同的数组:

console.log(filter);
// {article_id: {$in: [{$oid: "5dcd2a95d7e2999332441825"}, {$oid: "5dcd2a95d7e2999332441827"}, {$oid: "5dcd2a96d7e2999332441829"}]}}
但在这种情况下,我得到以下错误:

CastError:对于值“\”{$oid:\“5DCD2A95D7E29993244825\”}\“转换为ObjectId失败

尽管如此,如果我使用特定的控制台日志过滤器并将其作为过滤器在Studio 3T中传递,我确实会得到期望的结果


知道我在这种情况下做错了什么吗?

快来找我!我只是个大白痴。。显然,在
find()
方法-.-“…”之后添加了
.skip(10)
。。。。现在我明白了为什么返回0条记录。。。我在这上面花了好几个小时

对于将来的引用,如果在模式中定义,Mongoose会自动将字符串转换为ObjectID。因此,如果您不跳过前10条记录,则以下操作将完全正常工作:

const articles = ["5dcd2a95d7e2999332441825", 
                    "5dcd2a95d7e2999332441827", 
                    "5dcd2a96d7e2999332441829"]
filter.article_id = {
  $in: articles
};

return Product.find({ ...filter }) // Note that I DON'T put .skip() here..