保存猫鼬错误之前文档必须有一个_id

Ris*_*dey 3 mongoose mongodb node.js

我正在尝试创建一个架构。

我不断收到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);
Run Code Online (Sandbox Code Playgroud)

Ale*_*lex 5

http://mongoosejs.com/docs/guide.html#_id内容如下:

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

_id如果您在模式中显式定义类型,则您有责任设置它:

User._id = mongoose.Types.ObjectId('000000000000000000000001');
Run Code Online (Sandbox Code Playgroud)