bobbyz
bobbyz

Reputation: 5046

Setting own mongoose schema _id property

I've found a number of examples showing the ability to set your own _id property to something other than the default ObjectId in a mongoose schema:

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

A few questions I have:

1) Does this auto increment and handle everything else for me? The only examples I've seen don't show any additional code to ensure this a unique and incremented key in MongoDB.

2) This doesn't seem work for me. When I remove the _id from the schema, I get documents posting correctly as expected, but when I add it (_id: Number), nothing gets added to the collection, and Postman returns just an empty object {}. Here's the relevant code:

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);
        }
    });
});

A POST request returns {}, and neither the collection nor document are created.

Upvotes: 2

Views: 4242

Answers (1)

JoeTidee
JoeTidee

Reputation: 26054

If you include an _id field in your schema definition, when you insert a document you must supply it with your own manually generated _id. If you don't, the document will not get inserted.

Alternatively, if you do not include an _id field in your schema definition, Mongoose will create this for you automatically, when the document is inserted, and it will be of type ObjectId (which is the default way that MongoDB sets the _id field on documents).

Upvotes: 2

Related Questions