{
"_id" : ObjectId("64caa6599b2ec8d2da9e8e58"),
"message" : {
"text" : "hey"
},
"users" : [
{
"from" : "64c7acfbe872c97c7912ca09",
"to" : "64c2d5612172d620ac18714f"
}
],
"sender" : ObjectId("64c7acfbe872c97c7912ca09"),
"createdAt" : ISODate("2023-08-02T18:54:17.176+0000"),
"updatedAt" : ISODate("2023-08-02T18:54:17.176+0000"),
"__v" : NumberInt(0)
}
我想从“用户”访问“来自”和“到”。
const messages = await messageModel.find({
// first try
users: {
$all: [from, to],
},
// second try
// users: {
// $elemMatch: {
// from: from,
// to: to,
// }
})
.sort({ updatedAt: 1 })
console.log("messages=>" ,JSON.stringify(messages))
我尝试了两种方法,但无法访问用户数组,它返回空数组。 由于用户的数据类型是数组,它不允许我使用 $eleMatch。
消息模型
const mongoose = require("mongoose");
const messageSchema = mongoose.Schema(
{
message: {
text: {
type: String,
required: true,
},
},
users: Array,
sender: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
},
{
timestamps: true,
}
);
module.exports = mongoose.model("messages", messageSchema);
当您从数组中查询某些内容时,您无需遍历嵌入的数组,MongoDB 会自动为您完成。
这里可以直接在
"users.from": "the_obj_id"
上查询
例如。
const messages = await messageModel.find({
"users.from": "64c7acfbe872c97c7912ca09",
"users.to": "64c2d5612172d620ac18714f"
})
我正在链接另一个示例 https://mongoplayground.net/p/0HKyMOuXqdH
这解释了 MongoDB 如何自动从数组中提取值并匹配您的查询,而您无需手动遍历文档中的整个嵌入数组。