MongoDB - Error: document must have an _id before saving

后端 未结 6 1023
花落未央
花落未央 2020-12-30 03:48

I\'ve been struggling so much with this project. I am following a tutorial that is out of date in some areas, for instance their version of Jquery used a totally different f

相关标签:
6条回答
  • 2020-12-30 04:06

    _id is added automatically by MongoDb.

    If you want to keep _id on your data structure be sure to initialize correctly:

    var obj = new UserSchema({ 
        "_id": new ObjectID(), 
        "username": "Bill", 
        "password" : "...." 
    });
    
    0 讨论(0)
  • 2020-12-30 04:08

    Its pretty simple:

    1. If you have declared _id field explicitly in schema, you must initialize it explicitly
    2. If you have not declared it in schema, MongoDB will declare and initialize it.

    What you can't do, is to have it in the schema but not initialize it. It will throw the error you are talking about

    0 讨论(0)
  • 2020-12-30 04:09

    Try below snippet I wanted to name _id as userId you can do without it as well.

    var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;
    
    var UserSchema = new Schema({
        username: String,
        password: String
    });
    UserSchema.virtual('userId').get(function(){
        return this._id;
    });

    0 讨论(0)
  • 2020-12-30 04:11

    No need to specify the document _id in your model. The system generates the id automatically if you leave out the _id like so:

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

    That being said, if you still want to generate the _id yourself, see the answers above.

    0 讨论(0)
  • 2020-12-30 04:20

    You can write your model without _id so it will be autogenerated

    or

    you can use .init() to initialize the document in your DB.

    Like:

    const mongoose = require('mongoose');
    
    const UserSchema = mongoose.Schema({
      _id: mongoose.Schema.Types.ObjectId,
      username: String,
      password: String
    })
    
    module.exports = mongoose.model('User', UserSchema);
    

    and then

    const User = require('../models/user');
    
    router.post('/addUser',function(req,res,next){
    
      User.init() // <- document gets generated
    
      const user = new User({
        username: req.body.username,
        password: req.body.password
      })
    
      user.save().then((data)=>{
        console.log('save data: ',data)
       // what you want to do after saving like res.render
      })
    }
    
    0 讨论(0)
  • 2020-12-30 04:22

    In my case, I accidentally had the following at the end of my Schema. Removing that worked:

    { _id: false }
    
    0 讨论(0)
提交回复
热议问题