【发布时间】:2016-12-21 00:15:56
【问题描述】:
我知道这个问题已经存在,但我找到的解决方案对我不起作用。我正在 Node.js 中构建一个基本的创建函数。它首先检查对象是否已经存在,如果不存在,则创建一个。即使在每个条件中添加了 else if 和 return 后,我也会收到此错误。但似乎一切都被执行了。这是我的代码:
controllers/shop.js:
var Shop = require('../models/shop').model;
module.exports = {
create: function(req, res) {
if(typeof(req) != 'object')
return res.status(400).send({error: Error.InvalidInput});
if(req.body.name === null) return res.status(400).json({error: Error.missingParameter('name')});
Shop.findOne({name: req.body.name}, function(err, shop){
if(err) return res.status(500).json({error: Error.unknownError});
else if (shop) return res.status(409).json({error: Error.alreadyExists('Shop')});
}).exec(Shop.create({name: req.body.name}, function(err, shop) {
if (err) return res.status(500).json({error: Error.unknownError});
else if (shop) return res.status(201).json(shop);
else if (!shop) return res.status(400).json({error: Error.createFailed('Shop')});
}));
},
}
【问题讨论】:
-
你得到的回应是什么?
-
@Sam 错误:发送后无法设置标头。
标签: javascript node.js mongodb mongoose