Updating an object with a new key-value pair is not successful

Having Trouble Assigning a New Key and Value to an Object

I am facing an issue where I am trying to add a new key named CreatedUser with an object/array value to a post, but it doesn't seem to be working as expected. Can someone please assist me with this?

Below is the snippet of my code:

newPost = new PostsModel({
        title,
        content,
        price,
        recreater
      });
    }
    await newPost.save();

     let aggregateMatch = null;
     let user = null;
     if(recreater) {

       aggregateMatch = { $match: { _id: ObjectId(recreater) } };
        user = await UsersModel.aggregate([
       {
         $sort: {
           timestamp: -1
         }
       },
       aggregateMatch
       ])

      newPost.createdUser = user;
     }

    console.log("posts", newPost) //Unable to see the createdUser key

    res.out(newPost);

Answer №1

In order to add properties to a mongoose document, you must first convert it into a native JavaScript object.

const post = newPost.toObject();
post.createdUser = user;

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

What is the reason behind Chrome automatically refreshing the URL when no response is received for a certain amount of time

Within my node application, I have an anchor tag that, upon being clicked, triggers an Express GET route. This route then makes various API calls and displays the response within an EJS template. In cases where the API response from the Express route take ...

Which data store to use with Express on Node?

Embarking on my inaugural project with node/express. Considering implementing a data store and noticed express utilizing redis as a session store. Does this imply that redis comes pre-installed with express? Wondering if I should install mongodb, but if r ...

Retrieve items from an array within a nested MongoDB document

I've been struggling to find a solution for removing objects from arrays within embedded documents in MongoDB. In my schema, I have a user and an array of flower objects structured as follows: const UserSchema = new Schema({ name : { t ...

Strategies for transferring longer tasks in Express routes

My application utilizes Express as the user-facing framework for my REST API, along with RabbitMQ for RPC-like function calls to a clustered backend. Additionally, I utilize Q to promisify all workloads in the Routes. Within one of the Routes, there is fu ...

Methods for displaying data on the client side using express, MongoDB, and jade

I'm currently working on displaying data retrieved from my database using node.js, Express, and MongoDB. I successfully see the data in the console, but now I need to output it on the front-end using Jade. Here is the data I have retrieved: { date: ...

Refreshing a webpage with Socket.io

Currently, I am working on developing a one-to-one chat application that utilizes socket.io and mongodb. However, I have encountered an issue where a new socket connection is established every time the page is refreshed. Additionally, users need to refresh ...

Dealing with mongoDB Errors

Currently, I am in the process of setting up routes for login and sign up using NodeJs and Express. I have implemented error handling on the backend to display messages on the frontend. I have successfully handled all errors except one that is causing me ...

Within Node/Express, when accessing req.query.token, it returns as undefined when navigating to localhost:3000/?token=foobar

I'm facing an issue with parsing a URL in my Express backend. Whenever I visit a url like localhost:3000/token=myJwtToken, the value of req.query.token in my backend middleware authJwt.verifyToken is coming up as undefined. In my React App.js, I am m ...

Can a website built on Express.js be optimized for SEO?

Would pages created with the traditional route structure provided by Express (e.g. ) appear on Google's Search Engine Results Page as they would for a Wordpress blog or PHP website using a similar path structure? ...

Record a request using bunyan

Currently, I am developing an application using node.js and express. In the process, I have incorporated bunyan for logging purposes, but I'm facing difficulties in understanding how to log requests effectively. Let's say my router invokes a fun ...

Implementing Request and Transaction ID Logging with Winston on Node.js: A Step-by-Step Guide

After creating a Node JS REST service with Express, I encountered the need to log specific headers like 'X-org-ReqId' and 'X-org-Tid' in all log lines generated during the execution of each request. This contextual information is essent ...

Creating a route in keystone.js to handle numerical values

Currently revamping a Wordpress blog with Keystone.js and setting up archives. I am looking to implement a generic number detection to display the archive page instead of using 2012 specifically. It may not be the perfect solution, but it will suffice fo ...

Having trouble implementing connect-busboy in my Node.js application

Currently, I'm trying to implement image uploads in my node.js application using connect-busboy. Here's the code snippet I've written based on the reference guide https://www.npmjs.org/package/connect-busboy: router.post('/upload&apos ...

Incorporate create-react-app with Express

Issue - I am encountering a problem where I do not receive any response from Postman when trying to access localhost:9000. Instead of getting the expected user JSON data back, I am seeing the following output: <body> <noscript>You need to ...

Is it possible to run Angular2 and Expressjs on separate ports?

I have set up my Angular2 application to use Expressjs as the backend. Both projects are structured within the same directory: /index.html <-- Angular index file /app.js <-- Expressjs /package.json /Gruntfile.js /bin <-- Expressjs bin ...

Failed to load CSS file in nodeJS application

I followed a tutorial to create a backend app using nodeJS and Express. My MongoDB connection with Mongoose is working fine. However, I am facing issues when trying to add a simple front-end using html/ejs/css. The endpoints are loading on localhost but on ...

Having difficulties with implementing the throw await syntax in an async express handler in Node.js

const express = require("express"); const expressAsyncHandler = require("express-async-handler"); const app = express(); const func = async () => { return false; }; app.get( "/", expressAsyncHandler(async () => ...

Embedding a transpiled .js file in HTML using ExpressJS as a static resource

ExpressJS setup to serve transpiled TypeScript files is giving me trouble. Whenever I try to access /components/foo.js, I keep getting a 404 error. /* /dist/server.js: */ var express = require('express'); var app = express(); var path = requir ...

The overall behavior of MongoDB appears to be not quite as expected

When I first started using MongoDB, I was able to successfully connect. However, when I tried to execute a basic query like: db.users.find() I encountered an error message saying TypeError: Cannot read property 'find' of undefined, indicating t ...

Encountering a 400 error when posting with a React application using an Express server

Trying to troubleshoot why I keep receiving a 400 error, it's really frustrating. In my express server: const app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.post('/api/messages', (req ...