Setting own mongoose schema _id property

时间:2016-08-31 17:43:14

标签: javascript mongodb mongoose schema

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.

1 个答案:

答案 0 :(得分:1)

如果在架构定义中包含_id字段,则在插入文档时,必须为其提供自己手动生成的_id。如果不这样做,则不会插入文档。

或者,如果您未在架构定义中包含_id字段,则Mongoose会在插入文档时自动为您创建此字段,并且它将是ObjectId类型(即MongoDB在文档上设置_id字段的默认方式。)