MongoDB has encountered an issue where it is unable to create the property '_id' on a string

Currently, I am utilizing Node.js and Express on Heroku with the MongoDB addon. The database connection is functioning correctly as data can be successfully stored, but there seems to be an issue with pushing certain types of data.

Below is the database connection snippet:

mongodb.MongoClient.connect(mongoURI, function (err, database) {
if (err) {
    console.log(err);
    process.exit(1);
}

// Save database object from the callback for reuse.
db = database;
console.log("Database connection ready");

// Initialize the app.
var server = app.listen(process.env.PORT || dbport, function () {
    var port = server.address().port;
    console.log("App now running on port", port);
});
});

I have no issues when pushing my Twitter API response into the database using the following code:

db.collection(TWEETS_COLLECTION).insert(data);

(where 'data' is a JSON variable)

However, attempting to push another JSON variable within the same method results in an error. Here's the code snippet:

var jsonHash = '{"hashtag":"","popularity":1}';
var objHash = JSON.parse(jsonHash);
objHash.hashtag = req.body.hashtag;
JSON.stringify(objHash);
collection(HASHTAG_COLLECTION).insert(jsonHash);

And here is the error that occurs:

TypeError: Cannot create property '_id' on string '{"hashtag":"myhash","popularity":1}' at Collection.insertMany... ...

Any insights into what might be causing this issue?

Answer №1

It seems like there may be some confusion regarding the jsonHash variable in your code. It looks like unnecessary JSON handling is being done here. Additionally, it appears that you are inserting the incorrect variable – instead of jsonHash, you should be inserting objHash, which is the appropriate object to insert. Using JSON.stringify(objHash); doesn't serve any purpose as the returned JSON isn't being saved. Perhaps you intended something more along these lines?

var objHash = {
      hashtag: "",
      popularity: 1
};
objHash.hashtag = req.body.hashtag;
collection(HASHTAG_COLLECTION).insert(objHash);

Answer №2

jsonHash remains a string. Perhaps consider storing objHash without using JSON.stringify?

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

Exploring the process of assigning custom images to individual items within arrays in React JS

Within my Json file, I have an array that details the materials of various foods. When displaying these on my recipe page, each item of material should have a corresponding image. However, with numerous food items and materials, implementing this purely le ...

Developing a personalized error message pop-up system in Electron

I am currently in the process of developing an application for file backup, which involves a lot of reading and writing to the filesystem. While most parts of the app are functioning well, I am facing some challenges with error handling. In the image belo ...

Modify the image inside a div when hovering

How can I create a product card that displays thumbnails of images when hovered over, and changes the main image to the thumbnail image? My current challenge is getting this functionality to work individually for each card on an e-commerce site. Currently, ...

Developing an Android application with JSON integration: What is the best way to construct a JSON Object and JSON Array that aligns with a specific format using JSONObject and JSONArray data types

Is there a way to use JSON Objects and JSON Arrays in a way that matches this specific structure using the JSONObject and JSONArray Types? {"PeripheralList": [{"Category":"BP","CollectionTime":"2015-12-28T09:09:22-05:00", "DeviceInfo":null, "Rea ...

Transmitting intricate data sets to the WEB API

I am experiencing difficulties in sending a JSON complex object to my User control within my web API project. Every time I try, I encounter a 404 error. While controls with routes like /api/{control}/{action}/{id} are functioning properly, those with the r ...

What is the best way to conceal all input elements in a form?

I have been attempting to conceal input elements within my form by using the code snippet below. Unfortunately, it doesn't seem to be functioning as expected... <html lang="en"> <head> <title>example</title> < ...

The issue with GatsbyJS and Contentful: encountering undefined data

Within the layout folder of my project, I have a Header component that includes a query to fetch some data. However, when I attempt to log this.props.data in the console, all I get is 'undefined'. Could someone please point out where I might be m ...

Applying Tailwind styles to dynamically inserted child nodes within a parent div

Currently, I am in the process of transitioning my website stacktips.com from using Bootstrap to Tailwind CSS. While initially, it seemed like a simple task and I was able to replace all the static HTML with tailwind classes successfully. However, now I ha ...

Having trouble with React's conditional rendering not working as expected?

I am currently working on updating the contents of my Navbar and Router by using useContext and conditional rendering techniques. Here is a snippet from my App.js: import "./App.css"; import axios from "axios"; import { AuthContextProv ...

When I hover over div 1, I am attempting to conceal it and reveal div 2 in its place

I need help with a CSS issue involving hiding one div on mouse hover and showing another instead. I attempted to achieve this using pure CSS, but both divs end up hidden. Would jQuery be necessary for this task? Below is the CSS/HTML code I wrote: .r ...

How can I make multiple elements change color when hovering with CSS?

Hey there! I have a little design challenge that I need help with. On my website (), I am trying to make multiple elements of a specific item change color when the user hovers over the text. If you hover over the "more" menu item, you'll notice that o ...

Webpack has successfully built the production version of your ReactJS application. Upon review, it appears that a minified version of the development build of React is being used

Currently, I am implementing Reactjs in an application and the time has come to prepare it for production. In my package.json file, you can see that there is a "pack:prod" command which utilizes webpack along with a specific webpack.config.js file to build ...

Having difficulty implementing a personalized color scheme for the mui component

Attempting to set the background color as midnightBlue but encountering an error: Error: Cannot read properties of undefined (reading '100') Upon reviewing the syntax, no errors were found. Perhaps this issue stems from a dependency problem? ...

A pop-up window for selecting a file within an <a> tag

Is there a way to create an Open File dialog box on a link within my webpage? I attempted <input name="uploadedfile" type="file"> However, it only functions as a button and does not allow for the selection of multiple files. I would like somethin ...

Is there a way to link node.js with mongodb?

Looking to establish a connection between my node.js and MongoDB. --> Currently running MongoDB version 6.5.0 (installed as a service with complete setup) --> Installed mongosh (MongoDB terminal) for database access and modifications --> Successfu ...

Struggling to display the retrieved data on the webpage

Code in pages/index.js import React from 'react'; import axios from 'axios'; import ListProducts from '@/components/products/ListProducts'; const getProducts = async () => { const data = await axios.get(`${process.env.AP ...

Should we consider the implementation of private methods in Javascript to be beneficial?

During a conversation with another developer, the topic of hacking into JavaScript private functions arose and whether it is a viable option. Two alternatives were discussed: Using a constructor and prototype containing all functions, where non-API meth ...

When you access the `selectedIndex` property in JavaScript, it will return an object of type `HTMLSelect

I am currently working on a piece of code that retrieves the value from dropdown list items and then displays it in the document. To proceed, please select a fruit and click the button: <select id="mySelect"> <option>Apple</option ...

Encountering an issue while trying to utilize the firestorePlugin from vuefire in Vuejs 3 createApp. The problem is that I am receiving an Uncaught TypeError: Cannot set property '$

I recently encountered an issue in my Vue.js 3 app with the following code snippet in my main.js file: import { createApp } from "vue"; import App from "./App.vue"; import { firestorePlugin } from "vuefire"; const app = creat ...

The validation using regex is unsuccessful when the 6th character is entered

My attempt at validating URLs is encountering a problem. It consistently fails after the input reaches the 6th letter. Even when I type in "www.google.com," which is listed as a valid URL, it still fails to pass the validation. For example: w ww www ww ...