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!