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

问题描述 投票:0回答:3

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

我一直得到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);
node.js mongodb mongoose
3个回答
2
投票

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

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

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

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

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

0
投票

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

如果这不是问题,试试这个:

_id: { type: Mongoose.Schema.Types.ObjectId }
© www.soinside.com 2019 - 2024. All rights reserved.