Error validator failed for Mongo Db: Masekhta validation failed with error for _id field, expecting `_id`

I am struggling with creating simple scripts to add an object to MongoDB, and I keep encountering this error message:

Error: Masekhta validation failed: _id: Error, expected 
_id I can't figure out why this is happening. My guess is that it might be related to the unique validator, but I believe mongoose should handle the _id properly.

Here is the Schema:

const mongoose = require("mongoose");
const uniqueValidator = require("mongoose-unique-validator");

const Schema = mongoose.Schema;

const masekhtaSchema = new Schema({
  book: { type: String, required: true },
  pesukim: { type: String, required: false },
  selected: { type: Boolean, required: false },
});

masekhtaSchema.plugin(uniqueValidator);

module.exports = mongoose.model("Masekhta", masekhtaSchema);

Script:

const Masekhta = require("../models/masekhta");

const addMasekhta = async () => {
  const createdMasekhta = new Masekhta({
    book: "test",
    pesukim: "test",
    selected: false,
  });

  try {
    console.log("adding");
    await createdMasekhta.save();
  } catch (err) {
    console.log(err);
  }
};

addMasekhta();
Just to provide some context, I have another similar script that is functioning correctly, so the database connection seems to be set up properly.

If necessary, here is the full error:

Error: Masekhta validation failed: _id: Error, expected `_id` to be unique. Value: `60c1dbdc13a2a7392c0ac7ce`
    at ValidationError.inspect (C:\Users\Admin\Desktop\All Projects\Coding\In Progress\Syium\backsiyum\node_modules\mongoose\lib\error\validation.js:47:26)
    // Remaining stack trace omitted for brevity...
}

Answer №1

Looks like the source of this problem is related to mongoose-unique-validator. The problem has been discussed on Github. Since this package hasn't received any updates in the past 2 years, it's best to steer clear of it.

Answer №2

I encountered a similar issue, and found success with the following code:

await user.save({validatemodifyedOnly:true})

In your situation,

await createdMasektah.save({validatemodifyedOnly:true})

Hopefully this solution proves useful to others.

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

How can the callback from C++ be successfully installed in the Javaobject window within QtWebkit?

I have successfully implemented HTML-JS to call a C++ method using QtWebkit. Now, I want to send a callback from the C++ method to the JavaScript window. How can I achieve this? Below is my code snippet. #include <QtGui/QApplication> #include <Q ...

Working with external data in D3.js involves loading and manipulating datasets efficiently

As a newcomer to D3.js, I have been exploring various tutorials and exercises to familiarize myself with it. My primary goal with D3 is to load external data, typically in JSON format, and create interactive charts based on that data. You can find the bas ...

Replacing HTML text with JSON data can be easily achieved by using JavaScript

After receiving data from an API and converting it into JSON format, I encountered difficulty when attempting to change a selected element in HTML. Every time I tried to do so, I either got 'undefined' or 'Object Object' as the output. ...

Swap out a particular component during the testing phase

Currently, I am running tests on my React-Redux application using Jest. Within my API calls, I have integrated a fetch module called cross-fetch. However, I am looking to substitute this with fetch-mock. Take a look at my directory structure: Action.js i ...

Error occurs when passing a service as a parameter to a controller in AngularJS

After adding 'loginService' as a parameter to the controller in order to reference the service I want to use, I encountered an error that caused the rest of my angular functions to stop working. app.controller('loginController', functi ...

I continuously encounter "undefined" when attempting to retrieve collections

Despite my best efforts, I am unable to retrieve the data from the server using the snapshot docs. I have verified that the collection is named "creaciones" in lowercase. There is one document in the collection with existing data. I have double-checked fo ...

Can Jstree retain the selected options?

Currently, I am populating the jstree by using li and ul tags. My goal now is to keep track of the selections made by users and store them in a json format for future use. For instance, the jstree is initially loaded with some values. Later on, I would li ...

What causes arguments to be zeroed out during a WebAssembly imported function call?

I created a WASM module manually that can be decompiled using wasm2wat to reveal the code below. (module (type (;0;) (func)) (type (;1;) (func (param i32 i32))) (import "std" "print" (func (;0;) (type 1))) (func (;1;) (type 0) ...

Tips for displaying an HTML page using JavaScript

In my project, I am working with an .html file (File X) that needs to immediately open another .html file (File Y) based on a certain value. Could someone provide guidance on the best way to achieve this using JavaScript? Additionally, I would like the pa ...

"NodeJS applications using MongoDB always face the challenge of data expiring after only one

Utilizing the MongoDB npm module in my node application, I have implemented the following code to create a new item in the collection with a TTL index: var utcDate = new Date(); var emailObj = {email: emailAddress, createdAt: utcDate}; dbo.collection("ini ...

Is there a way to have my MUI Typography component display a unique image cursor when hovered over?

After some testing, I found that setting the cursor to cursor: pointer works perfectly fine. However, my goal is to use a custom image as a cursor. The image is saved in both my src and public folders, but I seem to be struggling with the syntax when using ...

Installing MongoDB on an Ubuntu machine is taking forever

Seeking advice on a more efficient method to install MongoDB on Ubuntu 12.04. Currently utilizing apt-get install mongodb-org, but experiencing extremely slow download speeds. Despite being on a fast connection, all other downloads are quick. Could it be ...

"Encountered an error: The function is not defined for password and re-entering password

I ran into this error message even after adding the javascript to my html code for registration. Unfortunately, none of the javascript functions or event listeners seem to be working as intended. As a beginner in learning about javascript and html, I would ...

What causes the Invalid Form Body error to appear when using the Discord API?

While developing a Discord bot, I encountered an issue with creating a ping command. The error message received was as follows: (node:37584) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body embed.footer.icon_url: Scheme "flashybot& ...

The Spring Data MongoDB push operation is failing to update multiple fields

I am working with a collection of data objects stored in MongoDB as follows: [ { "status" : "passed", "version" : "124" , "value" : 6 }, { "status" : "passed", "version" : "123" , "value" : 10 }, { "status" : "failed", "version" : "123" , "val ...

Displaying iframes in AngularJS using a service

I am currently developing an Angular app and encountering some difficulties with rendering a Soundcloud embed iframe in my HTML. The issue arises when I try to display the tracks stored in the array generated by my getTracks function. Despite successfully ...

Guide on setting up a new NPM and JavaScript project within Visual Studio 2015

Whenever I watch tutorials, they always mention having a "special npm reference" that I seem to be missing. https://i.sstatic.net/I52dn.png All I can find are the "normal" references (.net assemblies). I also can't locate any project type labeled as ...

trigger the focusout event within the focusin event

I am attempting to trigger the focusout event within the focusin event because I need to access the previous value from the focusin event, but the focusout event is being triggered multiple times. $('tr #edituser').focusin(function(){ var ...

Supabase authentication in a React app is causing a TypeError: Unable to access properties of undefined (specifically 'user')

In the development of my React application using Next.js, I've integrated Supabase for authentication. I've created a custom hook named useAuthentication to verify if the user is logged in and redirect them to the login page if they're not. ...

What is the correct way to handle fetch timeouts in a React component?

Utilizing a JavaScript timeout, I am able to fetch Dogs from my API successfully. However, there are instances where the timeout fails to clear properly: import { useState, useEffect, useCallback } from 'react'; const DogsPage = () => { c ...