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.