The mongoose.populate() method is failing to display the populated content

// defining user schema

const mongoose = require('mongoose');

const {ChatRoom} = require('./chatRoom');

const userSchema = new mongoose.Schema({

_id: mongoose.Schema.Types.ObjectId,
username:{
    type: 'String',
    unique: true,
},
collegeEmail:{
    type: String,
    unique: true,
},
password: String,
photo: String,
name: String,
phoneNo: Number,
collegeName: String,
gender: String,
chatList:[{userId:this, chatId:{type: mongoose.Schema.Types.ObjectId, ref: 'ChatRoom'}}],
bio: String,
follow:[ this],
following:[ this],
lastSeen: Number,
active: Boolean, 
status: Boolean,
otp: Number

});

const User = mongoose.models.User || mongoose.model('User', userSchema); module.exports = User;

//defining chatRoom schema

const mongoose = require('mongoose');

const User = require('./user');

//message schema

const chatMsgSchema = new mongoose.Schema({

_id: mongoose.Schema.Types.ObjectId,
sender: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
receiver: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
msg: String,
time: Number

});

const ChatMsg = mongoose.models.ChatMsg || mongoose.model('ChatMsg', chatMsgSchema);

//chatTable schema

const chatTableSchema = new mongoose.Schema({

_id: mongoose.Schema.Types.ObjectId,
chats:[{type: mongoose.Schema.Types.ObjectId, ref: 'ChatMsg'}],

});

const ChatRoom = mongoose.models.ChatRoom || mongoose.model('ChatRoom', chatTableSchema);

module.exports = {ChatRoom, ChatMsg};

// script for populating chatList

router.post('/room',ensureAuthenticated,async function(req, res) {

const id = req.body.id;
console.log(id);
const frnd = await User.
    findOne({username: req.user.username}).
    populate({
        path: 'chatList',
        model: 'ChatRoom',
        match: { _id: id}
    }).
    exec();
    console.log(frnd);

});

on the console show all chatList =>

No output from the populate and filter on the chatList was observed.

Answer №1

  1. Welcome to Stack Overflow
  2. Make sure to format your question when submitting it to SO, distinguishing between code and message.

Your code has several issues that need to be addressed:

Avoid defining _id in your schemas unless necessary for a specific problem.

Cleaning up the code would look like this:

// my user schema

import mongoose, { Schema } from 'mongoose';

const userSchema = new Schema({
  // properties
});

const User = mongoose.model('User', userSchema);
module.exports = User;

//msg schema

const chatMsgSchema = new Schema({
  // properties
});

const ChatMsg = mongoose.model('ChatMsg', chatMsgSchema);

//chatTable schema

const chatTableSchema = new Schema({
  // properties
});

const ChatRoom = mongoose.model('ChatRoom', chatTableSchema);

module.exports = { ChatRoom, ChatMsg };

// script for populate chatList

router.post('/room', ensureAuthenticated, async function(req, res) {
  const id = req.body.id;
  console.log(id);
  // logic here 
});

EDIT

Adjust how you're populating data in your script as follows:

router.post('/room', ensureAuthenticated, async function(req, res) {
  const id = req.body.id;
  console.log(id);
  // updated population logic
});

You may need to customize the provided samples accordingly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to retrieve nested data from a JSON API response?

Trying my hand at creating a basic CLI cryptocurrency tracker app. The app runs a successful API call and provides the following output: [ { exchange: 'binance', base: 'ADA', quote: 'BTC', price_quote: '0.000 ...

Tips for swapping out an item mid-scrolling?

What is the best way to change the navbar when scrolling a page in React? How can I achieve this while following React's concepts? Is using getElementById considered bad practice? const useState = React.useState const useEffect = React.useEffect con ...

Here's a guide on using a button to toggle the display of password value in Angular, allowing users to easily hide

I have successfully implemented an Angular Directive to toggle the visibility of password fields in a form. However, I am facing an issue with updating the text displayed on the button based on the state of the input field. Is there a way for me to dynami ...

delay in displaying options when toggling visibility in a dropdown menu

When you first click on the select, it displays incorrectly https://i.sstatic.net/Ax9T7j8J.png But when you click on it a second time, it displays correctly https://i.sstatic.net/UpW4krED.png $(document).on("click", "#edit_afpDetalle_mes&q ...

Guide on incorporating an Ajax spinner to a Slideshow

I am in need of assistance with creating a manual slideshow that includes an ajax loader image. The goal is to display the loader image every time I click on the Previous or Next buttons, until the Test 1, Test 2, and Test 3 texts are fully loaded. Any sug ...

Performing Jquery functions on several elements at once

Looking at the code snippet below, there are two buttons and an input in each container. The input calculates and adds up the number of clicks on the 2 buttons within the same container. However, it currently only works for the first container. How can thi ...

"Angular-chart is throwing an error with an undefined $scope.chart

I am having trouble creating a chart with an onClick event that can retrieve the label that was clicked. After searching, I found and modified a solution. Here is my code snippet: $scope.chart; $scope.onClick = function (points, evt) { console.log(po ...

Display everything when an option is clicked

I have a filter that is working perfectly. When I select a specific category, it filters out only rows with that category. However, I am stuck on how to display all rows again after clicking on the first option. My objective is to show all rows when "Categ ...

Tips for rearranging button placements by utilizing multiple owl carousels across various webpages

I have successfully implemented two owl carousels on my Shopify website, and they are both functioning properly. However, I am facing an issue with the navigation buttons on the second page. The navigation buttons seem to be picking up a style that I had i ...

Automatically resizing font to fit the space available

I am attempting to achieve the task described in the title. I have learned that font-size can be set as a percentage. Naturally, I assumed that setting font-size: 100%; would work, but unfortunately it did not. For reference, here is an example: http://js ...

Is it possible to capture a submit event from a form within an iframe using jQuery or JavaScript

If I have a webpage with an embedded iframe containing a form, how can I update a hidden field value on the main page once the form is submitted? What is the best way to trigger an event in the parent page upon form submission? Here's a simplified ex ...

Clicking on a date in Vue.js Fullcalendar

My goal is to retrieve a date value from the onDateClick function of fullCalendar using vue.js and then pass this data to a prop that can be stored in my backend via Laravel. However, I am encountering various undefined errors no matter how I approach th ...

Passing variables from ExpressJS to JavaScript can be a seamless process

I am struggling with this issue; I am utilizing NodeJS to retrieve a JSON and I must transfer the variable to my page for use by JavaScript. app.get('/test', function(req, res) { res.render('testPage', { myVar: 'My Dat ...

What is the best way to pass JavaScript object literals from a Node.js server to the frontend browser?

In Node, I am working with JavaScript object literals containing methods in the backend. For example: const report = { id: 1, title: 'Quarterly Report for Department 12345', abstract: 'This report shows the results of the sales ...

Put a cookie in place to deter users from returning to the website

Looking for a way to prevent access to my contest site once the form has been submitted. Is there a way to achieve this? Thanks in advance ...

Typescript gives you the ability to create a versatile writing interface that includes all

Think about this: interface Options { length?: number, width?: number } interface Action { performAction ({length, width}: Options): void } const myObject: Action = { performAction ({length, width}) { // do something without returning ...

Is it possible for two-way binding to function in index.html within Angular 4?

Does two-way binding function in index.html? I have some links and metadata in index.html. How can we define head parameters in a component? <head> <meta name="og:title" content={{titleValue}}> <meta name="og:url" content={{urlValue}}> & ...

Tips for transforming a React sign in component into an already existing Material UI sign in component

I am looking to revamp my current sign-in page by transitioning it into a material UI style login page. Displayed below is the code for my existing sign-in component named "Navbar.js". This file handles state management and includes an axios call to an SQ ...

What is the method for generating three inputs simultaneously in a single line?

I'm facing a challenge in my code where I want each line to contain only three input fields. Whenever I try to add a fourth input field, the first one remains on the previous line while the other three move to the next line. Oddly enough, this issue o ...

Modifying form data when submitting a form

Is there a common or widely-used method for modifying or adding form values before they are serialized and sent to the server upon form submission? I'm looking for a way to change or add these values without having to recreate them. I've come ac ...