Skip to content

Instantly share code, notes, and snippets.

@notdol
Created April 1, 2016 06:32
Show Gist options
  • Save notdol/f518152d8ee3ac331d5ca60320d43467 to your computer and use it in GitHub Desktop.
Save notdol/f518152d8ee3ac331d5ca60320d43467 to your computer and use it in GitHub Desktop.
if(req.body) {
connection.connect(dbConnectionStr + '/' + req.params.db, function (err, db) {
if (err) {
logger.error('Db open error: ' + err.message);
res.status(500).json({ message: 'Server error' });
return;
}
db.collection(req.params.collection, function(err, collection) {
if (err) {
logger.error('Error getting collection ' + collection + ': ' + err.message);
res.status(500).json({ message: 'Server error' });
return;
}
if(Array.isArray(req.body)){
// We only support inserting one document at a time
var totalCnt = req.body.length, currentIdx = 0;
var totalErr = []; var resultDoc;
function next(){
if(totalCnt == currentIdx) return finish(undefined,resultDoc);
collection.insert(
req.body[currentIdx++],
function(err,docs){
resultDoc = docs;
if(!err){
next()
}else{
finish(err,docs);
}
}
);
}
next();
}else{
collection.insert(req.body,finish);
}
function finish(err,docs){
if (err) {
logger.error('Error inserting into collection ' + collection + ': ' + err.message);
res.status(500).json({ message: 'Server error' });
return;
}
res.header('Location', '/'+req.params.db+'/'+req.params.collection+'/'+docs[0]._id.toHexString());
res.status(201).json({ ok: 1 });
}
});
});
} else {
res.json({ ok: 1 });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment