我正在使用mongoose在NodeJS和MongoDB中编写一个网站,我有一个模型 Photo ,另一个模型摄影师如下:
var photographerSchema = new Schema({
photographerId: Schema.Types.ObjectId,
emailAddress: { type: String, required: true, unique: true },
password: { type: String, required: true },
firstName: { type: String, default: '' },
lastName: { type: String, default: '' },
phoneNumber: { type: String, default: '' },
address: { type: String, default: '' },
profilePhoto: { type: String, default: 'media/UserPhotos' },
photos: { type: [photoSchema], default: [] }
});
var photoSchema = new Schema({
photoId: Schema.Types.ObjectId,
title: { type: String, default: '' },
path: { type: String, default: 'media/images' },
photographer: { type: photographerSchema, default: null },
isAppoved: { type: Boolean, default: false }
},
{ timestamps: true }
);
现在有问题了!当我想通过摄影师帐户添加多张照片时,给我错误 E11000重复密钥错误集合:test.photodatas索引:photographer.emailAddress_1 dup key:{:“photographeremail@email.com”}
任何帮助都让我感激不尽!谢谢!
答案 0 :(得分:0)
我假设您要为每张照片添加相同的对象,但是Mongoose正在尝试创建新的摄影师文档。在photoSchema中,你应该使用ref作为摄影师。
var photoSchema = new Schema({
photoId: Schema.Types.ObjectId,
title: { type: String, default: '' },
path: { type: String, default: 'media/images' },
photographer: { type: Schema.Types.ObjectId, ref: 'Photographer' },
isAppoved: { type: Boolean, default: false }
},
{ timestamps: true }
);
然后当您保存新照片时,只需在摄影师资产中使用photographer.photographerId
。
var photo = new Photo({
somedata: "data",
...
photographer: photographer.photographerId
});
然后当你想要拍摄所有照片时,你可以像这样填充摄影师:
Photo
.find()
.populate('photographer')
.exec(function (err, photos) {
// yey!
});