Struggling to fill in fields using express and Mongodb

I am facing an issue with populating the fields of two models, Post and User.

const PostSchema = new Schema({
    text: { 
        type: String 
    },
    author: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'user'
    }
})
const UserSchema = new Schema({
    username: {
        type: String, 
    }
})
router.post('/', async (req,res) => {
    try {
        let joe = new User({username: "joe"})
        await joe.save()
        
        let postText = {text: "my name is joe", author: joe._id}
        let postByJoe = new Post(postText)
        await postByJoe.save()

        let users = User.find().populate('author') 
        res.json({users})
    } catch (error) {
        console.error(error.message)
        res.json(error.message)
    }
    
})

I've encountered a strange error that I can't figure out. It seems to be related to JSON conversion. Any assistance would be highly appreciated.

"Converting circular structure to JSON\n --> starting at object with constructor 'NativeTopology'\n | property 's' -> object with constructor 'Object'\n | property 'sessionPool' -> object with constructor 'ServerSessionPool'\n --- property 'topology' closes the circle"

Answer №1

Your schema contains something unique - you can only populate the Schema.Types.ObjectId field within it. It appears that you are attempting to populate the author field of the Post model.

To correct this, replace this line

let users = User.find().populate('author')
with
let users = Post.find().populate('user')
. Your code should resemble the following:

router.post('/', async (req,res) => {
try {
    let joe = new User({username: "joe"})
    await joe.save()
    
    let postText = {text: "my name is joe", author: joe._id}
    let postByJoe = new Post(postText)
    await postByJoe.save()

   let data = await Post.find().populate('user') 
    // map through the object returned
    const users = data.map((user) => user)
    res.json({users})
} catch (error) {
    console.log(error.message)
    res.json(error.message)
}

})

For more information on mongoose population, visit this link.

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

Restricting the number of characters allowed for text messages and keeping track of the count

I am attempting to implement a character limiter for an html textarea using JavaScript. Additionally, I want to include a total character counter. Unfortunately, the code I have written isn't functioning as expected. Can anyone identify where my mist ...

Incorporate a personalized add-button into the material-table interface

My current setup includes a basic material-table structured like this: <MaterialTable options={myOptions} title="MyTitle" columns={state.columns} data={state.data} tableRef={tableRef} // Not functioning properly editabl ...

Node.js in action with XmlHttpRequest

I'm having trouble making an XMLHttpRequest call from my client-side JavaScript to my Node server. It seems like nothing is happening and I'm a bit new to this concept. Here's the JavaScript function I've written: function sendTokenToS ...

Tap and conceal feature on a mobile website

I seem to be facing a JavaScript challenge. On the desktop version of my website, I've managed to create a functionality where hovering over a button reveals some text, and clicking anywhere else on the site hides the text. However, I'm now stru ...

The functionality of ng-table appears to be compromised when working with JSON data

Currently, I am facing an issue while using a JSON file to populate data in my Angular ng-table. Even though the JSON data is being displayed in a regular table format, certain functionalities of ng-table like pagination and view limit are not functioning ...

Optimal Placement of CSS and index.html Files in ReactJS with Redux

Currently, my setup for the index.html file looks like this: <!doctype html> <html class="no-js" lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Pra ...

Is it possible to utilize Angular's $http.get method with a dynamic route

I recently started working with Angular and I'm trying to figure out how to retrieve data from a REST API using a scope variable to determine the URI for the GET request. Imagine that I have an array of numbers being generated by a service in my app ...

Uniquely combining multiple jQuery appendTo functions into a single call

Is it possible to optimize this code snippet: jQuery('<img />',{alt:"Logo",src:"img/logo.jpg"}).appendTo("#scrittacentro"); jQuery('<h1 />',{text:'THE LCARS COMPUTER NETWORK',class:'cLightOrange lcars'}) ...

Activating/Deactivating Checkbox using Jquery

I'm having trouble getting this code to function properly when there are multiple instances of datepicker on the page. When selecting the option "I currently work here," it is affecting all groups instead of just the current one, which is not the des ...

Middleware in action on all routers following its inclusion

I've encountered an issue when trying to add middleware in express.Router(). let router = express.Router(); let mid = function(req, res, next) { console.log("mid"); next(); } router.get("/", function(req, res) { ...

Challenge in WordPress Development

As a beginner in website building, I am looking to customize the background of my pages with a solid color. The current SKT Full Width theme I am using has an opaque background which is causing the text on my slider to blend in and not look appealing. All ...

EJS: Warning when the "<%= %>" tag is used multiple times within the code

I am currently working on incorporating EJS with Node.js and Express.js. I have defined an array variable called "kindOfDay" containing the names of days as strings, such as "Sun", "Mon"... Within the EJS views folder, there is a file named list.ejs. The i ...

Exploring sections of a GLTF import within the primary rendering loop (apologies for any beginner questions)

As a Unity developer venturing into learning Three.js, I've come across a seemingly simple yet frustrating issue. My goal is to import and animate a 3D logo consisting of four separate meshes (elem1 to elem4) in my Three.js application. After exporti ...

What is the best way to locate an item reference for a specific DOM element?

Imagine a vast DOM structure with approximately 10,000 HTML elements, including 1,000 span tags. None of the span elements have any identifiers and are buried deep within other objects with long, complex Xpath paths that are not user-friendly for selectio ...

Instructions for adjusting the size of my modal window when the keyboard appears?

While developing a next.js app, I encountered an issue with the chat modal. When the input field is in focus, I want to resize the modal height so that the keyboard popup does not hide the input field. I attempted to modify the DOM but could not get it to ...

The error message "Uncaught TypeError: Unable to retrieve the 'length' property of an undefined object in Titanium" has occurred

Here is the data I am working with: {"todo":[{"todo":"Khaleeq Raza"},{"todo":"Ateeq Raza"}]} This is my current code snippet: var dataArray = []; var client = new XMLHttpRequest(); client.open("GET", "http://192.168.10.109/read_todo_list.php", true); c ...

Scrolling horizontally in a container using the mouse wheel

Is there a way to enable horizontal scrolling in a div using the mouse wheel or drag functionality with jQuery? I attempted using draggable, but it did not work effectively in my specific code scenario. Currently, I have a horizontal scrollbar. Are there ...

Function in AngularJS to increment counts based on matching names

Check out my angular application on this Plunker link The text area in my app contains data in the format of (key, count). My goal is to sum up these values using the calc() function. When the user clicks the button, I want the total summation to be disp ...

Code for switching between accordion panels with a simple button press

I took some code snippets from a website and developed a shopping cart accordion module. The complete code is available on my CodePen profile, you can access it through this link: http://codepen.io/applecool/pen/YXaJLa <div class="summary"> <but ...

Different method of including the ng-click attribute on the body element

Greetings! I am currently developing a chrome extension and incorporating Angular to prevent any conflicts with other Angular pages. To avoid conflicts, I am attempting to set an ng-click on the body element. Here is the code snippet I used: var body = do ...