Saving Mongoose data without _id

I use mongoose with node.js. I do not want the input field to be written. I use this code to save my record without the _id field. But he gives an error

the document must have _id before saving

var mongoose = require('mongoose'); var Schema = mongoose.Schema; var PlayerSchema = new Schema({ player_id : { type: Number }, player_name : { type: String }, player_age : { type: Number }, player_country : { type: String } } , { _id: false } ); var Player = mongoose.model('Player', PlayerSchema ); var athlete = new Player(); athlete.player_id = 1; athlete.player_name = "Vicks"; athlete.player_age = 20; athlete.player_country = "UK"; athlete.save(function(err) { if (err){ console.log("Error saving in PlayerSchema"+ err); } }); 

I am using mongoose version 3.8.14

+5
source share
2 answers

Unfortunately, you cannot skip the primary key for the document, but you can override the contents of the primary key, you can define your own primary key for each document.

Try the following chart for her.

 var PlayerSchema = new mongoose.Schema({ _id : { type: Number }, player_name : { type: String }, player_age : { type: Number }, player_country : { type: String }, 

});

I replaced your player_id with _id . Now you control the primary key of the document, and the system will not generate a key for you.

There are some plugins that can also use autoincremet for your primary key. https://github.com/chevex-archived/mongoose-auto-increment . You can also try them.

Also, about the error you get: Any document is an object and must be wrapped inside curly brackets , you cannot define two independent objects in one document. So you get this error.

+2
source

Unable to save data without _id

-4
source

Source: https://habr.com/ru/post/1200497/


All Articles