Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - Error: document must have an _id before saving

Tags:

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 format for some functions and I had to do a lot of changing around. But I think I am down to one last major problem that I can't seem to find a fix for. In my Schema variable I've got the _id, username, and password types

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

but when I go to try to add a new user to my app, instead of getting the alert I am supposed to get, it pops up as [object Object] and nothing gets added to the database. Then this error pops up in the mongo cmd

"Error: document must have an _id before saving".

I've tried commenting out the _id line and I get the right message but still nothing shows up in my database.

like image 935
Matt Lee Avatar asked Aug 30 '17 05:08

Matt Lee


People also ask

What is _ID in mongoose?

Sep 3, 2019. By default, MongoDB creates an _id property on every document that's of type ObjectId. Many other databases use a numeric id property by default, but in MongoDB and Mongoose, ids are objects by default.

Can _ID be a string MongoDB?

Yes, you can. BTW, uniqueness guaranteed by mongodb. Because _id field has a unique index by default.

How can I tell when a document was created in MongoDB?

The _id field contains the date when the document was inserted into the collection. You can use the getTimestamp() method to extract the date from the ObjectId.


2 Answers

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

like image 179
dasfdsa Avatar answered Sep 16 '22 21:09

dasfdsa


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   }) } 
like image 37
rootfuchs Avatar answered Sep 17 '22 21:09

rootfuchs