I have a database in MongoDB with two collections: Users and Contacts. 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. 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':
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:
{
"contacts": null
}
How can I make for get in the response the contact that has as owner the id porvided before?
If anyone can help me I would be very grateful. Thanks!
CodePudding user response:
The null
suggests that the query yields no results at all (which is unrelated to .populate()
).
From what you're describing, you want to search for contacts where the owner matches a particular id, so the query should be:
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.
CodePudding user response:
try this
const contacts = await Contact.findOne({
owner: new ObjectId("631791f8d7342693105b6908"),
}).populate("owner");