不带_id的猫鼬数据保存 [英] Mongoose data saving without _id

查看:84
本文介绍了不带_id的猫鼬数据保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在node.js应用程序中使用猫鼬.我不想记录_id字段. 我正在使用此代码来保存没有_id字段的记录.但这给了错误

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

文档在保存之前必须具有_id

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);
            }
        });

我正在使用猫鼬版本3.8.14

I am using mongoose version 3.8.14

推荐答案

不幸的是,您不能跳过拥有文档的主键,但是可以覆盖主键的内容,可以为每个文档定义自己的主键.

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.

尝试以下模式.

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

} );

我用_id替换了您的player_id.现在,您可以控制文档的主键,并且系统不会为您生成密钥.

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.

有些插件还可以为您的主键执行autoincremet. https://github.com/chevex-archived/mongoose-auto-increment .您也可以尝试这些.

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.

另外,关于您得到的错误: 任何文档都是对象,应该包装在curly brackets内,您不能在同一文档中定义两个独立的对象.因此,您会收到此错误.

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.

这篇关于不带_id的猫鼬数据保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆