我在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幫助我。