早些时候,我使用这段代码进行db调用获取数据.

const projectOffering = await ProjectOfferingsBudgets.find({ objectiveId: tracker.objectives.map((id)=>id)  }).lean().exec();

"对象ID"是一种对象ID类型,也是我的跟踪器.目标包含一个id数组(ObjectID),因此我想从数据库中检索数据,其中该id数组与"ProjectOfferingsBudget"集合中的对象ID匹配.

但我的一位同事告诉我,这不会起作用,而是try 一下这段代码.

const projectOffering = await ProjectOfferingsBudgets.find({ objectiveId: { $in: tracker.objectives }  }).lean().exec();

I have tried to console the result of the 2 different codes but I am receiving the same results.
In the database, it matches 2 documents and I am getting those 2 documents in return for my code as well as my colleague's code.
So what I am asking is can we use map() inside find() method if not then why I am getting the accepted result?

推荐答案

mongoose find()是非常宽容的.虽然这似乎有违常理,但正如您已经发现的那样,在本例中传递一个数组,find()方法将非常好地工作.使用$in运算符更具语义,但下面的这些示例返回相同的结果.给定一个对象ID数组:

const arr = [
   new ObjectId("650ecb0f507561a33ce927aa"), 
   new ObjectId("65128fb671522f4d58dabd55")
];

这两个查询返回相同的结果:

const users1 = await Model.find({_id: arr}); //< Pass just the array

const users2 = await Model.find({_id: {$in: arr}}); //< Pass array using $in

回答你最后一个问题"So what I am asking is can we use map() inside find() method".是的,你可以运行一个函数,只要它的返回值是封闭函数所期望的参数,那么你当然可以调用它.

Javascript相关问答推荐

如果被1个Phaser JS抵消,我的倾斜碰撞

将下拉分区与工具提示结合起来

回归函数不会迭代到foreach中的下一个元素

使用JavaScript重命名对象数组中的键

Vue Quill css仅应用于我的第一个Quill Editor组件+如何自定义工具栏

reaction useEffect KeyDown for each 条目配音输出

GrapeJS -如何保存和加载自定义页面

MongoDB中的引用

使用javascript将Plotly Expandable Sparkline转换为HighCharter Plot在bslib卡中

当作为表达式调用时,如何解析方法decorator 的签名?

未捕获错误:[]:getActivePinia()被调用,但没有活动Pinia.🍍""在调用app.use(pinia)之前,您是否try 使用store ?""

处理时间和字符串时MySQL表中显示的日期无效

在react JS中映射数组对象的嵌套数据

查询参数中的JAVASCRIPT/REACT中的括号

OpenAI转录API错误请求

在不删除代码的情况下禁用Java弹出功能WordPress

当代码另有说明时,随机放置的圆圈有时会从画布上消失

在JS/TS中将复杂图形转换为数组或其他数据 struct

Pevent触发material 用户界面数据网格中的自动保存

不协调嵌入图片