我(尝试)使用mongoose,express和node构建API系统。现在我有两个模式:用户和事件。
用户架构:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
profileImage: {
data: Buffer,
contentType: String
},
isAdmin: {
type: Boolean,
'default': false
},
bio: {
type: String,
'default': ''
}
});
mongoose.model('User', userSchema);
事件架构:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = mongoose.model('User').schema;
var eventSchema = new Schema({
title: {
type: String,
required: true
},
date: {
type: Date,
'default': Date.now
},
place: {
type: String,
required: true
},
distance: {
type: String,
'default': '-1'
},
eventType: {
type: Number,
'default': 2 /* 0 = Asfalto, 1 = Trail, 2 = Otros */
},
attenders: [userSchema],
comment: {
type: String,
'default': ''
}
});
mongoose.model('Event', eventSchema);
然后我定义了一个控制器来管理某个端点上的POST请求。在我的控制器上,我只检查事件请求中的“标题”和“位置”字段,如下所示:
if (!req.body.title) {
response.sendJSON(res, 400, null, {"message": "title param is needed"});
return;
}
if (!req.body.place) {
response.sendJSON(res, 400, null, {"message": "place param is needed"});
return;
}
Events
.create({
title: req.body.title,
place: req.body.place
}, function(err, event) {
if (err) {
response.sendJSON(res, 400, null, err);
} else {
response.sendJSON(res, 201, event, null);
}
});
};
所以我发送请求,使用'标题':'示例标题','地点':'西班牙'作为身体参数。
第一个请求成功创建了新事件,但是nexts请求显示了这个错误:
"status": 400,
"error": {
"code": 11000,
"index": 0,
"errmsg": "E11000 duplicate key error index: som-passatge.events.$attenders.email_1 dup key: { : null }",
"op": {
"title": "Título de evento 22",
"place": "Valencia",
"_id": "56cc905d496141587dc47caf",
"comment": "",
"attenders": [],
"eventType": 2,
"distance": "-1",
"date": "2016-02-23T17:01:17.650Z",
"__v": 0
}
},
"response": null
我不知道我做错了什么......