Error encountered when trying to save Mongoose model - "Cannot use $inc on a non-numeric value"

Currently, I have set up 2 mongoose models in separate files.

const userSchema = new mongoose.Schema({
name:{type: String, required: true},
postHistory:[{type: mongoose.Schema.Types.ObjectId, ref: "Posts"}]
)};

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

const postSchema = new mongoose.Schema({
name:{type: String, required: true},
post:[{postName:String, postContent:String}]
)};

module.exports = mongoose.model("Posts", postSchema );

My goal now is to create a new post, save it, and ensure that the object id reflects in the user schema. Let's assume there is an async function where the model content is passed along with a user id for simplicity.

const post = new Posts({name:'John', post:[{postName:'My Comment', postContent:'My Full comment'}]);
await post.save();      <---This works as intended

const owner = await User.findById(userId);  <-- This retrieves the specific user the post belongs to

owner.postHistory.push(post);   <---Output now shows user with 1 post object within postHistory array

await owner.save();  <-- Error occurs here

The error arises at this point, throwing the following message:

message": "Cannot apply $inc to a value of non-numeric type. {_id: ObjectId('5e7908fd1e2e656d81a9ba05')} has the field '__v' of non-numeric type string"

I believe I have followed the correct process based on the mongoose documentation: Mongoose Model Ref

This error does not occur when there is already an array of post ids embedded within User.postHistory in MongoDB. It only happens when the User has an empty postHistory array (such as when the user associates their first post).

Any suggestions or insights on overcoming this issue?

Answer №1

Discovered the solution after a deep dive. It turns out that in my MongoDB setup, the _v property was mysteriously being stored as a string rather than an int32.

Upon closer inspection, I noticed that while one of my documents had _v as int32, another document had it as a string. Switching the type to int32 for the problematic document resolved the issue and now I can create references without any problems.

Sharing this insight in case it proves useful to others. Don't forget to verify the data types of your properties within each document.

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

Applying the `lean` method to Mongoose queries that retrieve arrays in TypeScript

When working with two Mongoose queries, I made the decision to utilize the .lean() method on both of them. It appears that using .lean() on a query that returns a single document works well: let something:Something; SomethingDocument.findOne({_id:theId}) ...

Activate text-entry fields after a button has been pressed on polymer 1.0

I am currently developing a project focused on creating a list of doctors using the Polymer 1.0 framework. Within the doctor-list, I have integrated a Vaadin grid called doctors-grid.html to display data sourced from a JSON file. Upon double-clicking on a ...

Using ID attributes to compare JavaScript Objects and generate a distinct list within Angular/JS

I am working with the github API to retrieve an array of objects containing commit data. My goal is to extract a unique list of commitors and format it as shown below to create a graph: {"id":temp,"label":temp,"type": "number","p": {} } Here is the code ...

Integrating a personalized dropdown feature into the Froala editor within an AngularJS environment

After searching for a JavaScript rich text editor that doesn't use frames and allows easy customization of the toolbar with custom dropdowns, I came across the Froala editor. It also offers AngularJS-friendly directives. Previously, I tried using Text ...

Search for documents in MongoDB where two fields have the same value, using $match and $eq

How can I retrieve all documents in a collection where the value of document.a is equal to the value of document.b? I attempted db.collection.aggregate([ { $match: { $eq: [ '$a', '$b' ] } }]) However, this query does not produce any ...

Arrange the parallel table columns within their own individual divs to be perfectly aligned

I have a layout with two divs stacked on top of each other, each containing a table with the same number of columns. I need to ensure that the columns in both tables are the same width and aligned properly. If a column in one table expands, I want the corr ...

Utilize absolute positioning within Three.js to ensure that all objects are anchored at the 0,0,0 coordinate point

I am facing an issue where the solutions provided do not seem to work for me as I am new to Three.js. In my scene, I have several objects such as a map with each region represented by a separate object positioned on a plane. Here is an image of my setup: ...

Creating SVG Lines with Google Maps JavaScript API v3

I have a project that requires a dashed line between two points on Google Maps using JavaScript v3. The specification states that each dash should be 100px long. I have attempted to achieve this using SVG, but the dashes are not displaying correctly. Here ...

Filter an array containing nested objects based on dynamically determined properties

I'm working with an array of N objects and need to create a filter using JSON.stringify that dynamically checks multiple properties. Looking for a solution that is dynamic and doesn't rely on static properties (as shown in the code snippet above ...

React.Js custom form validation issue in Next.Js - troubleshooting required

My attempt at validating a form is causing some issues. After refreshing the page and clicking on the submit button, only the last input's error is generated instead of errors for every input according to the validation rules. Here is a screenshot o ...

Guide on scraping a site that employs Direct Web Remoting (DWR) for generating Javascript to interact with the HTML content of the page

When trying to crawl a specific website that appears to generate its content dynamically using DWR, I encountered a challenge. The source code of the page only reveals a minimal amount of HTML as a 'shell', without any useful links for crawling. ...

Exploring the capabilities of utilizing filters within a ternary operator in AngularJS

Can a filter be applied to a variable in the template within a ternary operation? <img ng-src="{{ image_url && image_url|filter:"foo" || other_url }}"> In this scenario, the filter is custom-made and I prefer not to alter it to accommodate ...

The standard TextField functionality was disrupted by the update to MUI v5

After typing a comment in the TextField and trying to click Done, nothing happens because the TextField still has focus. The first click removes the focus, while a second click is needed to complete the action. https://i.sstatic.net/XJvp0.png <TextF ...

Move the remaining blocks after deletion

Is there a way to create a seamless effect when removing an element? I am looking to incorporate a transition or slide effect when deleting a block and causing the blocks below it to move up smoothly. const animateCSS = (element, animation, prefix = &ap ...

The issue of Ejs partial header and footer file only functioning in one file and not the other (both at the same directory level)

I'm in the process of setting up a view page for a post on the main page of a website. Both pages share the same header and footer files, located at the same directory level. However, while one page is functioning correctly, the other is not. The erro ...

Search for Azure Time Series Insights (TSI) data insights

Is there a way to access real-time data from Azure TSI using the TSI query API? I am currently utilizing the TSI JavaScript Client library, which provides two wrappers for the Query API. However, these wrappers only allow me to retrieve aggregate data li ...

Tips on searching for an entry in a database with TypeScript union types when the type is either a string or an array of strings

When calling the sendEmail method, emails can be sent to either a single user or multiple users (with the variable type string | string[]). I'm trying to find a more efficient and cleaner way to distinguish between the two in order to search for them ...

How can I use the Grails Asset plugin to reference a static HTML file?

Currently, I am working with Grails 2.4.1 and have incorporated version 1.9.7 of the Grails Asset Pipeline Plugin. In my project, there is a javascript file that defines an AngularJS directive. This Javascript file needs to access a static HTML template f ...

javascript path as the first argument and callback as the last argument

Currently, I am in the process of creating a wrapper function for expressjs's app.get method. In these methods such as get, you can provide the path, some options, and then the callback. However, it is possible to omit the options and still have it w ...

JavaScript - Marking selected text: What are the options?

I am looking to implement a feature in JavaScript (without jQuery) that will allow me to highlight selected text with control points or markers (left and right). These markers should function similar to those on mobile phones, allowing me to extend the sel ...