Mongoose data saving without _id

匿名 (未验证) 提交于 2019-12-03 02:30:02

问题:

I am using mongoose with node.js application. I don't want _id field in record. I am using this code to save my record without _id field. But it is giving error

document must have an _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

回答1:

Unfortunately, You can not skip having a primary key for the document but you can override the primary key content, you can define your own primary key for each document.

Try the following schema for the same.

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

} );

I have replaced your player_id with _id. Now you have control over the primary key of the document and the system won't generate the key for you.

There are some plugins which can also do the autoincremet for your primary key. https://github.com/chevex-archived/mongoose-auto-increment. You might try these as well.

Also, about the error you are getting : Any document is an object and should be wrapped inside the curly brackets you can not define two independent object in the same document. So you are getting this error.



回答2:

It's impossible to save data without _id



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!