繁体   English   中英

Mongoose,按数组中的元素查找

[英]Mongoose, find by element in array

我正在尝试使用 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);
    }
  });

这会打印一个空数组,即使这个 id 在customers数组中显然有一个文档。 这似乎应该有效,但我显然错过了一些难题。 对我做错了什么的任何见解将不胜感激。

编辑:如果有人想/愿意进行更深入的研究,可以在此处找到该应用程序的 GitHub 存储库。 有问题的查询位于 routes/routes.js 的第 111 行(截至撰写本文时)。

另一个编辑:这似乎与相关字段的架构类型有关。 我消除了customers字段中条目的ref属性,以防万一导致问题,但我的查询仍然返回一个空数组。 下一个测试是向我的模型中添加一个新字段myStrings: [String] 然后我将一个字符串添加到我的 Appt 文档之一的数组中, "working" ,并查询Appt.find({myStrings: "working"}) ,这最终返回了我更新的 Appt 文档。 这告诉我使用mongoose.Schema.Types.ObjectId ,但我不知道如何解决它。

最终编辑:经过多次磨难,这已经解决了。 问题如下......为了测试,我使用 MongoDB shell 向我的数据库添加项目,它不像 Mongoose 那样强制执行数据类型。 我没有意识到我只是将用户 ID 作为字符串添加到customers数组中。 当猫鼬去寻找 ObjectIds 时,当然没有找到,并返回一个空数组。 使用db.appts.updateOne({<whatever information>},{$push:{customers: new ObjectId(<id string>)}})将客户添加到customers数组中,Mongoose 能够返回我正在寻找的信息.

我会说你的问题是你在过滤器中使用了一个字符串,其中该字段是ObjectId类型。 因此,您需要先将字符串转换为 ObjectId,以便 mongoose 能够正确查询。

Appt.find({ customers: mongoose.Types.ObjectId("5e7e3bc4ac4f196474d8bf69") }, (err, docs) => {});

添加 _id 字段:

Appt.find({ customers._id: "5e7e3bc4ac4f196474d8bf69" }, (err, docs) => {
if (err) {
  console.log(err);
} else {
  console.log(docs);
}});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM