node.js - 通过数组 mongoose 中的 id 查找对象
问题描述
我的聊天对象有一个包含两个元素的数组 - 用户 ID。我有来自 url 参数的第一个 id,但我在用户数组中有第二个 id。现在我想从 url 获取第一个 id 是这个,第二个在数组中的所有聊天。我认为我尝试这样做的示例将是对这个问题的最佳解释:
Chat.find({
users: { $all: [req.params.id, { $in: usersIdArray }] }
})
其中 usersIdArray 是例如:
[ 5f8777a01d8c122e74cb6f08, 5f8777721d8c122e74cb6f02 ]
它们是数字,而不是字符串。不知道是不是很重要...
我现在得到的错误:
(node:12168) UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "{ '$in': [ 5f8777a01d8c122e74cb6f08, 5f8777721d8c122e74cb6f02 ] }" at path "users" for model "Chat"
还有我的聊天模式:
// Create schema
const ChatSchema = new Schema({
users: {
type: [{
type: Schema.Types.ObjectId,
ref: 'Users',
}, {
type: Schema.Types.ObjectId,
ref: 'Users',
}],
required: [true, 'Podaj uczestników czatu.'],
},
lastMessage: {
type: Schema.Types.ObjectId,
ref: 'Message'
}
}, { timestamps: opts });
解决方案
由于数组的长度是固定的 (2),因此您可以根据数组位置进行查询:
Chat.find({
"users.0": req.params.id,
"users.1": {$in: usersIdArray}
});
如果这不起作用,那么可能是因为usersIdArray
实际上不是 ObjectId,在这种情况下,您需要映射它们:
usersIdArray.map(x => ObjectId(x))
推荐阅读
- javascript - 如何过滤对象数组,其中对象内的数组包含另一个数组中的所有项目?
- sql - SQL 使用临时表创建视图
- javascript - Node.js Mongodb 连接池 app.get 怎么做?
- python - 在 Scrapy/Selenium 中执行 Javascript POST 请求
- azure-devops - 如何在部署时使用 azure devops helm 任务更新 helm 图表名称
- gcc - 如何判断我需要什么版本的 libfortran
- python - 如何在python中对图像进行结构性OCR?
- css - 是否可以仅自动“伸缩”具有大内容的元素?
- asynchronous - 异步下载大量文件
- elixir - 使用 FunWithFlags 在 Absinthe 中间件中获取 ArgumentError ets.lookup