mongooseJS 在数组中查找带有 ID 的文档 [英] mongooseJS find docs with IDs in an array

查看:33
本文介绍了mongooseJS 在数组中查找带有 ID 的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要撤回 ID 存储在 ObjectIds 数组中的文档所以我有一个id"(123),我想要所有租户"的数组元素为(123)

I need to pull back documents that have ID stored in an array of ObjectIds so I have an "id" (123) and I want all the DOcs where the "tenants" have an array element of (123)

数据看起来像这样

{
  "_id": ObjectId("abc"),
  "name": "Miroslav",
  "tenants": [
    ObjectId("123"),
    ObjectId("456")
  ]
}

{
  "_id": ObjectId("abd"),
  "name": "Lothar",
  "tenants": [
    ObjectId("123"),
    ObjectId("694")
  ]
}

当然是mongoDB systax

of course the mongoDB systax

things.find( { 'tenants': ObjectId(123) } )

工作正常.

猫鼬抱怨

ReferenceError: ObjectId is not defined

所以我试过了

things.find( { 'tenants': mongoose.Schema.ObjectId(123) } )

在集市上,猫鼬返回了除预期的 2 之外的所有记录.

And in a bazaar twist, mongoose returned ALL records EXCEPT the 2 expected.

我在 3 年前看到过这个问题,那个帖子没有答案,希望这里有人能提供解决方案.

I've seen this question posted 3 years ago, and that post didn't have an answer, hopefully someone here will have a solution.

我正在使用猫鼬":4.9.8"(由于特定的承诺"问题,目前我无法升级版本)

Im using "mongoose": "4.9.8" (due to a specific 'promise' issue I cannot go up a version, at the moment)

谢谢

推荐答案

转换为ObjectId需要使用:

to convert to ObjectId you need to use:

things.find({tennants: mongoose.Types.ObjectId("123")});

mongoose.Schema.ObjectId 和 mongoose.Types.ObjectId 的区别在于后者是 ObjectId 构造函数.它甚至可以像这样使用:

the difference between mongoose.Schema.ObjectId and mongoose.Types.ObjectId is that the latter is the ObjectId constructor function. it can even be used like:

var id = new mongoose.Types.ObjectId("123");

创建一个 objectId 并将其存储在 id 变量中.

to create an objectId and store it in the id variable.

而 mongoose.Schema.ObjectId(或 mongoose.Schema.Types.ObjectId)指的是一种数据类型.这就是您在架构中使用的内容.与您设置的方式相同

while mongoose.Schema.ObjectId (or mongoose.Schema.Types.ObjectId) refers to a data type. that's what you'd use in your schema. the same way you might set

name: String

在架构中,您使用 mongoose.Schema.Types.ObjectId 来指定数据类型是 mongoose ObjectId.

in a schema, you use mongoose.Schema.Types.ObjectId to specify that the data type is a mongoose ObjectId.

注意:我记得几个月前在文档中读过这个,但我现在找不到文档了,我认为我的解释相当充分

note: I remember reading this in the docs a few months ago, but i was unable to find the docs now, i think my explanation is fairly adequate though

这篇关于mongooseJS 在数组中查找带有 ID 的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆