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.
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.
Yes, you can. BTW, uniqueness guaranteed by mongodb. Because _id field has a unique index by default.
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.
Its pretty simple:
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
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 }) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With