2015-10-23 42 views
1

我在express.js中使用mongodb有一個簡單的學生數據庫程序。如何對以下程序執行更新操作: 我的app.js程序如下:如何在express.js中更新操作

var studentDb=new StudentDb('localhost',27017); 
app.get('/',function(req,res){ 
    studentDb.findAll(function(error,stu){ 
    res.end(JSON.stringify({ 
     title:'students', 
     students:stu 
    })); 
    }); 
}); 

app.get('/student/new',function(req,res) 
{ 
    var rollno=req.param('rollno'); 
    studentDb.findByrollno(rollno,function(error,docs) 
    { 
    if(error) { res.end(JSON.stringify(error)); }else{ 
     if(docs.length==1) 
      {res.end('already has one.');} 
     else 
     { studentDb.save({ 
       title:req.param('title'), 
       name:req.param('name'), 
       rollno:req.param('rollno') 
      }, 
      function(error,docs) 
      { 
      console.log(docs); 
      });setTimeout(function(){ res.redirect('/');},5000);}} 


    }); 
}); 
app.delete('/student/new', function (req, res) { 

    studentDb.findByrollno(req.param('rollno'), function (error, docs) { 
     studentDb.delete(req.param('rollno'),function (error,students) { 
      if (error) { 
       console.log(error); 
      } else { 
       console.log("deleted rollno: " + req.param('rollno')); 

      } res.end(JSON.stringify(students)); 
     }); 
    }); 
}); 

here is my studentdb.js file 

var Db = require('mongodb').Db; 
var Connection = require('mongodb').Connection; 
var Server = require('mongodb').Server; 
var JSON = require('mongodb').JSON; 
var ObjectID = require('mongodb').ObjectID; 

StudentDb = function(host, port) { 
    this.db= new Db('studentdata', new Server(host, port, {safe: false}, {auto_reconnect: true}, {})); 
    this.db.open(function(){}); 
}; 


StudentDb.prototype.getCollection= function(callback) { 
    this.db.collection('students', function(error, student_collection) { 
    if(error) callback(error); 
    else callback(null, student_collection); 
    }); 
}; 
StudentDb.prototype.findAll = function(callback) { 
    this.getCollection(function(error, student_collection) { 
     if(error) callback(error) 
     else { 
     student_collection.find().toArray(function(error, results) { 
      if(error) callback(error) 
      else callback(null, results) 
     }); 
     } 
    }); 
}; 
StudentDb.prototype.findByrollno = function(rollno,callback) { 
    this.getCollection(function(error, student_collection) { 
     if(error) callback(error) 
     else { 
     student_collection.find({rollno:rollno}).toArray(function(error, results) { 
      if(error) callback(error) 
      else callback(null, results) 
     }); 
     } 
    }); 
}; 
StudentDb.prototype.save = function(students, callback) { 
    this.getCollection(function(error, student_collection) { 
     if(error) callback(error) 
     else { 
     if(typeof(students.length)=="undefined") 
      students = [students]; 

     for(var i =0;i< students.length;i++) { 
      student = students[i]; 
      student.created_at = new Date(); 
     } 

     student_collection.insert(students, function() { 
      callback(null, students); 
     }); 
     } 
    }); 
}; 
StudentDb.prototype.delete = function(rollno,callback) { 
    this.getCollection(function(error, student_collection) { 
     if(error) callback(error) 
     else { 
     student_collection.remove({rollno:rollno},function(error, results) { 
      if(error) callback(error) 
      else callback(null, results) 
     }); 
     } 
    }); 
}; 

我需要更新學生數據庫中的一個字段,但我不知道使用更新query.pls幫助我。

回答

0

你的意思是你不知道如何實現StudentDb.update方法?你只需要使用Mongo的更新操作符創建一個對象。有關於如何使用這些here的好文檔。此方法將更新一個學生設置,您在學生updatedFields對象設置任何字段:

// updatedFields should be an object with fields to set on the student 
// e.g. updatedFields = {name: "Bob", favouriteSubject: "Computing"} 
StudentDb.prototype.update = function(rollno, updatedFields, callback) { 
    this.getCollection(function(error, student_collection) { 
    if(error) callback(error) 
    else { 
     student_collection.updateOne(
     {rollno: rollno}, 
     {$set: updatedFields}, 
     callback 
    ); 
    } 
    }); 
}; 

注意,因爲你的回調按照callback(err, result)約定沒有必要打電話給他們自己,你可以將它們傳遞給蒙戈調用他們爲你。

0

從MongoDB的文檔:

db.collection.update(
    <query>, 
    <update>, 
    { 
    upsert: <boolean>, 
    multi: <boolean>, 
    writeConcern: <document> 
    } 
) 

來源:MongoD docs

您可以創建你的StudentDb對象原型的新方法來處理更新操作:

StudentDb.prototype.update = function (rollno, updatedFields, callback) { 
    this.getCollection(function(error, student_collection) { 
    if(error) callback(error); 
    else { 
     student_collection.update({rollno: rollno}, updatedFields, function (err, updatedStudent) { 
     if (err) callback(err); 
     else callback(null, updatedStudent); 
     }); 
    } 

添加一個新的處理程序到您的路由器使用PUT HTTP動詞:

app.put('/student/new', function (req, res) { 
    studentDb.update(req.param('rollno'), req.body, function (err, student){ 
    if (err) { 
     console.error(err); 
    } else { 
     res.send(JSON.stringify(student)); 
    } 
    }); 
}); 

作爲旁註,您可以查看nodejs的mongoose模塊,直接使用MongoDB本地驅動程序稍微冗長些。

也看到你對nodejs相當陌生,我建議閱讀更多關於RESTful服務的內容類型HTTP頭並以JSON格式發送你的數據。

響應HTTP請求時(例如,如果更新操作失敗,讓客戶知道這件事),改善你的錯誤處理:

studentDb.update(req.param('rollno'), req.body, function (err, student){ 
    if (err) { 
     console.error(err); 
     res.status(500).json(err); // respond with HTTP status 500 (internal server error) 
    } else { 
     console.log("updated rollno: " + req.param('rollno')); 
    } res.send(JSON.stringify(student)); 
    }); 
相關問題