【问题标题】:document must have an _id before saving mongoose error在保存猫鼬错误之前,文档必须有一个_id
【发布时间】:2020-10-23 15:05:55
【问题描述】:

我正在尝试创建架构。

我不断收到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


    【解决方案1】:

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

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

    如果您在架构中明确定义 _id 类型,则设置它是您的责任:

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

    【讨论】:

      【解决方案2】:

      _id 是 mongoDB 中文档的主键。您不必在 Schema 中指定 _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);
      

      【讨论】:

      • 需要为子文档设置参考
      【解决方案3】:

      我认为您不需要定义_id。尝试不使用,看看它是否有效。

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

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

      【讨论】:

        【解决方案4】:

        如果你想在你的模式中明确定义_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');
        

        【讨论】:

          【解决方案5】:

          简单地从代码中删除该行

          _id: mongoose.Schema.ObjectId
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2022-01-10
            • 2023-02-22
            • 2017-12-05
            • 1970-01-01
            • 1970-01-01
            • 2019-01-22
            • 2014-01-29
            • 2019-07-14
            相关资源
            最近更新 更多