简体   繁体   English

Mongoose,按数组中的元素查找

[英]Mongoose, find by element in array

I'm trying to find all documents with a certain value in an array field using Mongoose and Node.js.我正在尝试使用 Mongoose 和 Node.js 在数组字段中查找具有特定值的所有文档。 I can do this in MongoDB with no trouble, but I'm having difficulty in Mongoose.我可以在 MongoDB 中毫无问题地做到这一点,但我在 Mongoose 中遇到了困难。 I used Find document with array that contains a specific value as my guide for how to do this, but I'm not getting the results I expect.我使用Find document with array that contains a specific value作为如何执行此操作的指南,但我没有得到我期望的结果。 My model:我的型号:

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;

I want to find all documents that contain a certain customer id.我想查找包含某个客户 ID 的所有文档。 In MongoDB shell, this is what I would do:在 MongoDB shell 中,这就是我要做的:

db.appts.find({customers: "5e7e3bc4ac4f196474d8bf69"})

This works as expected, giving me all documents, (one document in this case), where this id is in the customers array.这按预期工作,为我提供了所有文档(在本例中为一个文档),其中此 ID 位于customers数组中。

{ "_id" : ObjectId("5e7e719c806ef76b35b4fd69"), "customers" : [ "5e7e3bc4ac4f196474d8bf69" ], "full" : false, "store" : "Nashville", "dotw" : "Friday", "month" : 4, "day" : 15, "hr" : 13, "min" : 0 }

In Mongoose, this is what I'm trying:在猫鼬中,这就是我正在尝试的:

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

This prints an empty array, even though there is clearly a document where this id is in the customers array.这会打印一个空数组,即使这个 id 在customers数组中显然有一个文档。 This seems like this should work, but I'm clearly missing some piece of the puzzle.这似乎应该有效,但我显然错过了一些难题。 Any insight into what I'm doing wrong would be very much appreciated.对我做错了什么的任何见解将不胜感激。

Edit: In case anyone would like to/be willing to take a more in-depth look, a GitHub repo of the app so far can be found here .编辑:如果有人想/愿意进行更深入的研究,可以在此处找到该应用程序的 GitHub 存储库。 The query in question is in routes/routes.js at line 111 (as of the time of writing).有问题的查询位于 routes/routes.js 的第 111 行(截至撰写本文时)。

Another edit: It appears this has something to do with the Schema type of the field in question.另一个编辑:这似乎与相关字段的架构类型有关。 I eliminated the ref attribute of the entries in the customers field, just in case that was causing a problem, but my query still returned an empty array.我消除了customers字段中条目的ref属性,以防万一导致问题,但我的查询仍然返回一个空数组。 The next test was to add a new field to my model, myStrings: [String] .下一个测试是向我的模型中添加一个新字段myStrings: [String] I then added a string to the array of one of my Appt documents, "working" , and queried Appt.find({myStrings: "working"}) and this finally returns the Appt document that I updated.然后我将一个字符串添加到我的 Appt 文档之一的数组中, "working" ,并查询Appt.find({myStrings: "working"}) ,这最终返回了我更新的 Appt 文档。 This tells me there's something squirrely about working with the mongoose.Schema.Types.ObjectId , but I can't figure out how to resolve it.这告诉我使用mongoose.Schema.Types.ObjectId ,但我不知道如何解决它。

FINAL EDIT: After much tribulation, this is solved.最终编辑:经过多次磨难,这已经解决了。 The issue was as follows... For testing, I was adding items to my database using MongoDB shell, which does not enforce data types like Mongoose does.问题如下......为了测试,我使用 MongoDB shell 向我的数据库添加项目,它不像 Mongoose 那样强制执行数据类型。 I didn't realize that I was simply adding user ids as strings to the customers array.我没有意识到我只是将用户 ID 作为字符串添加到customers数组中。 When Mongoose went looking for ObjectIds, of course it didn't find any, and returned an empty array.当猫鼬去寻找 ObjectIds 时,当然没有找到,并返回一个空数组。 Adding customers to the customers array with db.appts.updateOne({<whatever information>},{$push:{customers: new ObjectId(<id string>)}}) , Mongoose was able to return the information I was looking for.使用db.appts.updateOne({<whatever information>},{$push:{customers: new ObjectId(<id string>)}})将客户添加到customers数组中,Mongoose 能够返回我正在寻找的信息.

I would say your problem is that you are using a String in the filter, where the field is of ObjectId type.我会说你的问题是你在过滤器中使用了一个字符串,其中该字段是ObjectId类型。 Therefore, you need to convert the string to ObjectId first for mongoose to be able to query it correctly.因此,您需要先将字符串转换为 ObjectId,以便 mongoose 能够正确查询。

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

add the _id field:添加 _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