我有mongodb集合的mongoose模式,我定义如下:
var userSchema = new mongoose.Schema({
username: {type: String, unique : true},
password: {type: String},
firstname: String,
lastname: String,
sketches: [{name: String, sketch: Array}]
});
var User = mongoose.model('User', userSchema);
在数据库集合中,我目前有一个文档,其中包含除sketches
之外的所有属性的值以用于测试目的。我有一个服务器端点,在调用时应该发出PUT请求来更新文档并将对象添加到草图数组中:
app.route("/addSketch/:username").put(function(req, res) {
var user_name = req.params.username;
User.findOne({username:user_name},function(err,foundObject){
if(err){
console.log("error");
res.status(500).send();
}
else{
if(!foundObject){
res.status(404).send();
}
else{
if(req.body.strokes && req.body.sketchName){
var sketchObj = [];
sketchObj[req.body.sketchName] = req.body.strokes;
foundObject.sketches.push(req.body.sketchData);
}
foundObject.save(function(err,updatedObject){
if(err){
console.log(err);
res.status(500).send();
}
else{
res.send(updatedObject);
}
});
}
}
});
console.log('saving on server');
var form = formidable.IncomingForm();
console.log(form);
console.log('the type of the request received is', (typeof req));
form.parse(req, function(err, fields, files) {
res.writeHead(200, {"content-type": "text/plain"});
res.write('received upload:\n\n');
var name = fields.name;
var newSketch = new SavedSketch();
newSketch.name = name;
newSketch.sketchData = fields.value;
newSketch.save(function(err,savedObject){
if(err){
console.log(err);
res.status(500).json({status:'failure'})
}
else{
console.log("ID: " + fields.value.id + " strokeData:" + fields.value.strokes);
res.json({status: 'success'});
}
});
res.end();
});
});
在这个网络服务中,我实际上是试图通过用户名选择用户文档,该用户名作为参数传递给url字符串,如下所示:
http://localhost:11235/addSketch:testname
出于某种原因,当我尝试使用带有以下正文的邮递员发出PUT请求时,我收到404错误:
{"sketchName" : "tempName", "strokes":[1,2,3,4,5]}
文档本身包含以下数据:
{
"lastname" : "name",
"firstname" : "test",
"password" : "password123",
"username" : "testname",
"_id" : ObjectId("57c4d7693aa85cea2acf4d4d"),
"sketches" : [],
"__v" : 0
}
Web服务本身的逻辑是否存在阻止文档被发现的错误?
答案 0 :(得分:1)
404未找到错误,表示路线不可用。
将您的网址更改为:
http://localhost:11235/addSketch/testname
此后您不会收到404错误。我希望这会有所帮助。
编辑:解决500错误问题
您正在草图数组中以错误的格式推送对象。
替换:
var sketchObj = [];
sketchObj[req.body.sketchName] = req.body.strokes;
foundObject.sketches.push(req.body.sketchData);
。通过强>
foundObject.sketches.push({"name" : req.body.sketchName,"sketch" :req.body.strokes});
这可以解决你的500错误。