mongoose中通过new Model()得到的对象的存储的疑问
发布于 7 年前 作者 q86002618 3635 次浏览 来自 问答

在通过Model的构造函数得到的对象执行save方法时,mongoose是否会自动对数组中的对象添加_id字段?如果是这样,为什么会这样?

team Model的Schema

const teamSchema = new Schema({
	owner:{
		id:Schema.Types.ObjectId,
		name:String,
	},
	leader:[
		{
			id:Schema.Types.ObjectId,
			name:String,
			taskCode:[
				{
					type:String,
				}
			],
		}
	],
	teammate:[
		{
			id:Schema.Types.ObjectId,
			name:String,
			taskCode:[
				{
					type:String,
				}
			],
		}
	],
	...
	})

然后在执行

let teammate = [ { id: 59e8b4cf464f301bdc4379a4, name: 'useruser1' },
     { id: 59e8b4cf464f301bdc4379a5, name: 'useruser2' },
     { id: 59e8b4cf464f301bdc4379a6, name: 'useruser3' },
     { id: 59e8b4cf464f301bdc4379a7, name: 'useruser4' } ]
const newTeam = new Team({teamName,owner,leader,teammate,teamPlace,teamClass})
	newTeam.save()
	log(newTeam)

之后,log的结果是

{ 
...
  teammate:
   [ { id: 59e8b4cf464f301bdc4379a4,
       name: 'useruser1',
       _id: 59e8b4d0464f301bdc4379ac,
       taskCode: [] },
     { id: 59e8b4cf464f301bdc4379a5,
       name: 'useruser2',
       _id: 59e8b4d0464f301bdc4379ab,
       taskCode: [] },
     { id: 59e8b4cf464f301bdc4379a6,
       name: 'useruser3',
       _id: 59e8b4d0464f301bdc4379aa,
       taskCode: [] },
     { id: 59e8b4cf464f301bdc4379a7,
       name: 'useruser4',
       _id: 59e8b4d0464f301bdc4379a9,
       taskCode: [] } ],
...

实在想不明白,为什么teammate数组里面的对象会多出一个_id字段出来,求助各位大佬

5 回复

前排水果瓜子

首先你自定义的id有问题应该用

let teammate = [ { id: new mongoose.Types.ObjectId, name: 'useruser1' },

看文档 http://mongoosejs.com/docs/guide.html#_id

const teammateSchema = new Schema({
        name:String,
    },{_id:false});
    const teamSchema = new Schema({
        teammate:[teammateSchema]
    });

by the way:

参数:versionKey:String|Boolean

默认存储的数据里面带有有__v:0,用于版本控制,是否修复过该数据:

var schema = new Schema({ name: String });
var Thing = mongoose.model('Thing', schema);
var thing = new Thing({ name: 'mongoose v3' });
thing.save(); // { __v: 0, name: 'mongoose v3' }

// customized versionKey
new Schema({name:String}, { versionKey: '_somethingElse' })
var Thing = mongoose.model('Thing', schema);
var thing = new Thing({ name: 'mongoose v3' });
thing.save(); // { _somethingElse: 0, name: 'mongoose v3' }

当然你可以可以取消掉这个字段:

new Schema({name:String}, { versionKey: false });
var Thing = mongoose.model('Thing', schema);
var thing = new Thing({ name: 'no versioning please' });
thing.save(); // { name: 'no versioning please' }

@chenyulun 谢谢哥😊

来自酷炫的 CNodeMD

这个字段对数据没影响吧

回到顶部