Reputation: 33
I am trying to create a schema.
I keep getting the document does not have an _id
error, besides the code below I did try to initialize it explicitly, but nothing works.
var UserSchema = new mongoose.Schema({
_id: mongoose.Schema.ObjectId,
username: String,
password: String
});
var User = mongoose.model('user', UserSchema);
Upvotes: 3
Views: 11064
Reputation: 8055
simple remove the line from your code
_id: mongoose.Schema.ObjectId
Upvotes: 0
Reputation: 109
if you want to define _id in your schema explicity you should assign a value to "_id" for each insertation. you have two way to solve this problem : 1. remove "_id" from your schema and mongoose generate id automatically. 2. assign a value to _id :
var ObjectId = require('mongodb').ObjectID; // or var ObjectId = require('mongoose').Types.ObjectId; "but the first worked for me"
User._id = objectId('1111111111111111111');
Upvotes: 0
Reputation: 358
_id is the primary key for document in a mongoDB. You don't have to specify the _id in your Schema. It will be added automatically once the document is created.
Here is the sample code:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = new Schema({
username: {
type: String
},
password: {
type: String
}
});
module.exports = mongoose.model('User', User);
Upvotes: 1
Reputation: 37048
http://mongoosejs.com/docs/guide.html#_id reads:
Mongoose assigns each of your schemas an _id field by default if one is not passed into the Schema constructor.
If you explicitly define _id
type in the schema, it's your responsibility to set it:
User._id = mongoose.Types.ObjectId('000000000000000000000001');
Upvotes: 5
Reputation: 46
I think you dont need to define the _id. Try without and see if it works.
Also if that is not the problem try this:
_id: { type: Mongoose.Schema.Types.ObjectId }
Upvotes: 0