【问题标题】:Setting own mongoose schema _id property设置自己的猫鼬模式 _id 属性
【发布时间】:2017-01-08 09:58:08
【问题描述】:

我发现了一些示例,展示了将您自己的 _id 属性设置为 mongoose 架构中默认 ObjectId 以外的其他内容的能力:

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

我有几个问题:

1) 这会自动递增并为我处理其他所有事情吗?我见过的唯一示例没有显示任何额外的代码来确保这是 MongoDB 中唯一且递增的键。

2) 这似乎对我不起作用。当我从架构中删除 _id 时,我会按预期正确发布文档,但是当我添加它 (_id: Number) 时,没有任何内容添加到集合中,并且 Postman 只返回一个空对象 {}。以下是相关代码:

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

POST 请求返回{},既不创建集合也不创建文档。

【问题讨论】:

    标签: javascript mongodb mongoose schema


    【解决方案1】:

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

    或者,如果您没有在架构定义中包含 _id 字段,Mongoose 会在插入文档时自动为您创建此字段,其类型为 ObjectId(这是默认的MongoDB 在文档上设置_id 字段)。

    【讨论】:

    • 这是有道理的。现在我只需要查找一些最佳实践来创建您自己的 id 属性并保持正确的增量等......
    猜你喜欢
    • 1970-01-01
    • 2019-12-05
    • 2015-03-17
    • 2018-07-09
    • 2022-01-12
    • 2011-11-14
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多