在保存mongoose错误之前,文档必须有_id

时间:2018-02-08 17:11:15

标签: node.js mongodb mongoose

我正在尝试创建架构。

我一直收到document does not have an _id错误,除了下面的代码我尝试明确初始化它,但没有任何效果。

var UserSchema = new mongoose.Schema({
     _id: mongoose.Schema.ObjectId,
     username: String,
     password: String
 });

var User = mongoose.model('user', UserSchema);

5 个答案:

答案 0 :(得分:2)

http://mongoosejs.com/docs/guide.html#_id读到:

  

默认情况下,如果未将一个模式传递给模式构造函数,则Mongoose会为每个模式分配一个_id字段。

如果您在架构中明确定义_id类型,则您有责任进行设置:

User._id = mongoose.Types.ObjectId('000000000000000000000001');

答案 1 :(得分:1)

_id是mongoDB中文档的主键。您不必在架构中指定_id。创建文档后,它将自动添加。

以下是示例代码:

var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var User = new Schema({
  username: {
    type: String
  },
  password: {
    type: String
  }
});


module.exports = mongoose.model('User', User);

答案 2 :(得分:0)

我认为你不需要定义_id。试试没有,看看它是否有效。

如果这不是问题,请尝试:

_id: { type: Mongoose.Schema.Types.ObjectId }

答案 3 :(得分:0)

如果要在架构中显式定义_id,则应为每次插入将一个值分配给“ _id”。您有两种方法可以解决此问题: 1.从架构中删除“ _id”,猫鼬会自动生成ID。 2.为_id分配一个值:

var ObjectId = require('mongodb').ObjectID; // or  var ObjectId = require('mongoose').Types.ObjectId; "but the first worked for me"
User._id = objectId('1111111111111111111');

答案 4 :(得分:0)

简单地从代码中删除行

_id: mongoose.Schema.ObjectId