Creating a custom _id property for a mongoose schema

I have come across multiple instances where it is possible to set a custom _id property in a mongoose schema, rather than using the default ObjectId:

var personSchema = new mongoose.Schema({
    _id: Number,
    name: String
});

I have a couple of questions regarding this:

1) Does this auto-increment and take care of everything else for me? The provided examples do not include any extra code to ensure that this key is unique and incremented in MongoDB.

2) I am facing an issue with this. When I exclude the _id from the schema, documents are posted correctly as expected. However, when I include it (_id: Number), nothing gets added to the collection, and Postman returns an empty object {}. Here is the relevant code snippet:

var personSchema = new mongoose.Schema({
    _id: Number,
    name: String
});

var Person = mongoose.model("Person", personSchema);

app.get("/person", function (req, res) {
    Person.find(function (err, people) {
        if (err) {
            res.send(err);
        } else {
            res.send(people)
        }
    });
});

app.post("/person", function(req, res) {
    var newPerson = new Person(req.body);

    newPerson.save(function(err) {
        if (err) {
            res.send(err);
        } else {
            res.send(newPerson);
        }
    });
});

Upon making a POST request, only an empty object {} is returned, with neither the collection nor document being created.

Answer №1

When defining your schema, you have the option to include an _id field. If you choose to include it, you will need to manually generate a value for it when inserting a document. Failure to do so will result in the document not being inserted.

On the other hand, if you decide not to include an _id field in your schema, Mongoose will automatically create one for you upon insertion. This generated _id will be of type ObjectId, following MongoDB's default approach to setting the identifier on documents.

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

Utilizing a React component for interactive button functionality

In my React app, I decided to enhance my buttons by incorporating images using SVG. After discovering that I needed a separate component for my SVG files, I came across this helpful resource and created my own <SVGIcon /> component. However, when at ...

Delaying UI interactivity until the document is fully loaded

I'm currently developing a web application that must be compatible with Internet Explorer 8 (yes, you read it right, compatible with the HELL). The issue I'm facing is with uploading a file which is later processed by PHP code and then refreshes ...

The distortion of Blender animation becomes apparent once it is imported into three.js

I've been working on a project where I'm incorporating animations into a scene using a combination of blender and three.js. It took me several hours of trial and error to finally get the model and animation successfully imported into three.js. I ...

Master the art of displaying complete text when zooming in and elegantly truncating it when zooming out

I am currently working on a data visualization project using d3.js. The tree chart that I have created is functioning well, but I would like the text to react dynamically when zooming in and out. You can find the code for my project on this JSFiddle page. ...

Choosing various li classes within a navigation bar

Struggling to pick the right JQuery elements for my portfolio site. The aim is to show/hide the .inner (Task) items by clicking on the .outer (Category) items, complete with rotating .arrows when the menu expands. Check out a similar question, along with ...

redux reducer failing to update state within store

I am completely new to redux and still have a lot to learn. I am currently working on a project that requires setting up a redux store and using state from that store. However, as I try to update the state through a reducer, the code fails to work properly ...

Obtaining data from an ajax request in node.js

My webpage has a feature that triggers an ajax request: $.ajax({ type: 'POST', url: '/usernamecheck', data: {"username":username}, success: function(taken){ ...

Discovering the method to read a file that is currently downloading in either JavaScript or Python

Imagine a scenario where I am actively downloading a file while simultaneously wanting to read its contents. However, the file is being continuously updated during the download process. For instance, if I start reading the file when the progress bar shows ...

An efficient method for changing the letter case of object variables

My current task involves handling a relatively large JavaScript object with 50 keys retrieved from an API. I need to remap the variable naming convention to fit our code's variable convention. At the moment, my approach looks like this: let newObject ...

Updating the object in router.get and res.render in Node.js and Express after loading

When loading the page, I encounter an error with req.body.firstname.length inside router.use. The error states: TypeError: Cannot read property 'length' of undefined The issue arises because the default value is undefined for the input form. ...

image source that changes dynamically with a placeholder image

Currently, I am facing a certain issue. Unfortunately, I cannot provide a plunkr example as the image is sourced from a protected site and there are no open URLs available that constantly serve changing images. Additionally, I am unable to use a local anim ...

Steps to Create Javascript Image Zoom Effect on Mouse Hover

Looking to implement a feature on my website located at www.thetotempole.ca/javas2.html/. Basically, I have a table with images and I want them to enlarge when a user hovers over them and return to normal when the cursor is moved away. Is there a way to ac ...

Tips for retrieving the value sent via an AJAX $.post request in a PHP file

Here is an example of my Ajax call: var keyword = $('#keyword').value; $.post("ajax.php?for=result", {suggest: "keyword="+keyword}, function(result){ $("#search_result").html(result); }); In the PHP file, I am trying to ret ...

What is causing my ajax request to malfunction?

I'm encountering an issue while trying to send a request using AJAX. The request is successful when I use the following webservice: https://jsonplaceholder.typicode.com/users However, when I attempt to make the same request with my own service, I fac ...

Show a compact graphic in the upper-right-hand corner

Hey, I have this interesting idea but CSS isn't my strong suit. Any thoughts on how to achieve it? I'm looking to create a new class that, when applied to an item (like a div), displays a small clickable pre-defined image in the Top-Right corne ...

What is the process for setting up MongoDB replicaset with elastic IPs on EC2?

Summary: How can I properly utilize an elastic IP in my MongoDB replicaset setup? We currently have a MongoDB replicaset consisting of three nodes running on EC2. Recently, one of the instances within the set was decommissioned by AWS, leading us to stop ...

What steps do I need to follow in order to incorporate the SQLite database into my application?

My attempt to establish a database connection with my system is met with an issue where, upon calling the function, the application's browser displays this message: The "granjas" table is empty Below is the code snippet for reference: In JavaScript ...

Utilizing Google+ Snippet and Open Graph Protocol for Enhanced Visibility

I am currently facing an issue with my dynamically built web page where the links shared on Google+ are not showing snippets properly. I have followed the example snippet for article rendering and documentation provided here: https://developers.google.com ...

In a Vue serverless web application, OpenLayers Map object fails to trigger events

In my Vue serverless web application, I have implemented an OpenLayers map initialized in the mounted lifecycle method. The map is populated with ImageWMS layers that are updated by various functions. After updating the parameters of these layers, I call ...

In Typescript, we can streamline this code by assigning a default value of `true` to `this.active` if `data.active

I am curious if there is a better way to write the statement mentioned in the title. Could it be improved with this.active = data.active || true? ...