【发布时间】:2020-07-08 17:10:09
【问题描述】:
我正在尝试使用 Mongoose 和 Node.js 在数组字段中查找具有特定值的所有文档。我可以在 MongoDB 中毫无困难地做到这一点,但我在 Mongoose 中遇到了困难。我使用Find document with array that contains a specific value 作为我如何做到这一点的指南,但我没有得到我期望的结果。 我的模型:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const ApptSchema = new Schema({
store: { type: String, required: true },
dotw: { type: String, required: true },
month: { type: Number, required: true },
day: { type: Number, required: true },
hr: { type: Number, required: true },
min: { type: Number, required: true },
customers: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
full: { type: Boolean, required: true, default: false }
});
const Appt = mongoose.model("Appt", ApptSchema);
module.exports = Appt;
我想查找所有包含特定客户 ID 的文档。在 MongoDB shell 中,我会这样做:
db.appts.find({customers: "5e7e3bc4ac4f196474d8bf69"})
这按预期工作,为我提供了所有文档(在本例中为一个文档),其中此 id 在 customers 数组中。
{ "_id" : ObjectId("5e7e719c806ef76b35b4fd69"), "customers" : [ "5e7e3bc4ac4f196474d8bf69" ], "full" : false, "store" : "Nashville", "dotw" : "Friday", "month" : 4, "day" : 15, "hr" : 13, "min" : 0 }
在猫鼬中,这是我正在尝试的:
Appt.find({ customers: "5e7e3bc4ac4f196474d8bf69" }, (err, docs) => {
if (err) {
console.log(err);
} else {
console.log(docs);
}
});
这会打印一个空数组,即使在 customers 数组中明确有一个文档,该 id 也是如此。
这似乎应该可行,但我显然错过了一些难题。非常感谢任何对我做错了什么的见解。
编辑:如果有人想/愿意进行更深入的研究,到目前为止可以找到该应用程序的 GitHub 存储库here。有问题的查询位于第 111 行的 routes/routes.js 中(截至撰写本文时)。
另一个编辑:这似乎与相关字段的架构类型有关。我消除了customers 字段中条目的ref 属性,以防万一这会导致问题,但我的查询仍然返回一个空数组。下一个测试是在我的模型中添加一个新字段myStrings: [String]。然后,我在我的一个 Appt 文档 "working" 的数组中添加了一个字符串,并查询了 Appt.find({myStrings: "working"}),这最终返回了我更新的 Appt 文档。这告诉我使用mongoose.Schema.Types.ObjectId 有一些奇怪的地方,但我不知道如何解决它。
最终编辑:经过多次磨难,这个问题解决了。问题如下...
为了测试,我使用 MongoDB shell 将项目添加到我的数据库中,它不像 Mongoose 那样强制执行数据类型。我没有意识到我只是将用户 ID 作为字符串添加到 customers 数组中。当 Mongoose 去寻找 ObjectIds 时,它当然没有找到,并返回一个空数组。使用db.appts.updateOne({<whatever information>},{$push:{customers: new ObjectId(<id string>)}}) 将客户添加到customers 数组中,Mongoose 能够返回我正在寻找的信息。
【问题讨论】:
-
查询正确 (mongoplayground.net/p/Q9firU4-_0l),请确保您从 Mongoshell 和 mongoose 查询相同的数据库/集合。
-
感谢您的建议。这绝对是同一个数据库/集合。如果我查询
Appt.find({ _id: "5e7e719c806ef76b35b4fd69" }),我会返回与 MongoDB shell 查询db.appts.find({_id: ObjectId("5e7e719c806ef76b35b4fd69")})相同的文档,其中包含我在customers数组中寻找的用户。 -
这个答案给你三个解决这个问题的方法:stackoverflow.com/questions/63368225/…
-
This answer 给你三个解决这个问题的办法。
标签: arrays node.js mongodb mongoose