简体   繁体   English

ZCCADCDEDB567ABAE643E15DCF0974E503Z 填充响应返回 null

[英]Mongoose Populate response returns null

I have a database in MongoDB with two collections: Users and Contacts.我在 MongoDB 中有一个数据库,其中有两个 collections:用户和联系人。 In my project I have two models: User and Contact.在我的项目中,我有两个模型:用户和联系人。 Every User has an array with his contacts and every contact has a property owner that stores the id of the user that contains that contact.每个用户都有一个包含他的联系人的数组,每个联系人都有一个属性所有者,该所有者存储包含该联系人的用户的 ID。 These are my models:这些是我的模型:

 export const contactSchema = new Schema({ phoneNumber: { type: String, required: true, }, owner: { type: Schema.Types.ObjectId, ref: "User", }, }); const Contact = model("Contact", contactSchema, "contacts"); const userSchema = new Schema({ phoneNumber: { type: String, required: true, unique: true, }, password: { type: String, required: true, }, contacts: [{ type: Schema.Types.ObjectId, ref: "Contact" }], }); const User = model("User", userSchema, "users"); export default User;

Now, I'm trying to make a function that receives a request, response and next function and returns in the response an array with all the contacts of the user id '631791f8d7342693105b6908':现在,我正在尝试制作一个接收请求、响应和下一个 function 的 function 并在响应中返回一个包含用户 ID '631791f8d7342693105b6908' 的所有联系人的数组:

 import { NextFunction, Request, Response } from "express"; import Contact from "../../../database/models/Contact/Contact"; const getContacts = async (req: Request, res: Response, next: NextFunction) => { const contacts = await Contact.findOne({ _id: "631791f8d7342693105b6908", }).populate("owner"); res.status(200).json({ contacts }); }; export default getContacts;

In my mongoDB I have a contact that contains the owner with that id, but when I make the request the response is:在我的 mongoDB 中,我有一个联系人,其中包含具有该 ID 的所有者,但是当我提出请求时,响应是:

 { "contacts": null }

How can I make for get in the response the contact that has as owner the id porvided before?我如何才能在响应中获取之前提供的 id 作为所有者的联系人?

If anyone can help me I would be very grateful.如果有人可以帮助我,我将不胜感激。 Thanks!谢谢!

The null suggests that the query yields no results at all (which is unrelated to .populate() ). null表明该查询根本不产生任何结果(与.populate()无关)。

From what you're describing, you want to search for contacts where the owner matches a particular id, so the query should be:根据您的描述,您想要搜索所有者与特定 ID 匹配的联系人,因此查询应该是:

const contacts = await Contact.findOne({
  owner: "631791f8d7342693105b6908",
}).populate("owner");

As you state in your comment, use .find() if you want to find all contacts belonging to a particular owner.当您在评论中使用 state 时,如果您想查找属于特定所有者的所有联系人,请使用.find()

try this

 const contacts = await Contact.findOne({ owner: new ObjectId("631791f8d7342693105b6908"), }).populate("owner");

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

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