Mongoose簡單使用

 Mongoose簡單使用

本文僅作入門級參考,具體深入請自行研究官方API(http://mongoosejs.com/docs/api.html)

 

一、加載mongoose模塊

var mongoose = require('mongoose');

 

二、連接mongo數據庫

IP'localhost'

數據庫名:'quizpractice'

    //db = mongoose.createConnection('localhost', 'quizpractice');

var db ;

try{

   db = mongoose.connect('mongodb://localhost/quizpractice');

}catch(err){

    console.log("err:"+err);

}

 

三、建立mongoose數據庫模版

var answerSchema = new mongoose.Schema({

    O_id: 'String',

    studentid:'String',

    questionid:'String',

    answer:'String',

    isright:'String',

    rightanswer:'String',

    lesson_uuid:'String',

    totaltime:'String'

})

Answer = db.model('Answer', answerSchema);

 

四、存儲數據

數據庫表名:'Answer'(如果存在,直接將data插入,如果不存在,新建此表插入data

Answer = db.model('Answer', answerSchema);

//將需插入的數據data轉化爲模版

var ans = new Answer(data);

//插入數據庫

ans.save(function (err) {

if (err){

console.log('save error');

}else{

console.log('save success');

} // TODO handle the error  

});

 

五、刪除數據

刪除條件:conditiondata格式參照模版,字段可爲空)

Answer.remove(condition, function (err, ans) {

if (err) return handleError(err);

//下面代碼僅爲證明已刪除

    console.log("kitten._id:"+ ans._id);// undefined

    Answer.findById(kitten._id, function (err, ans) {

        console.log("ans:"+ ans) // null

    })

});

 

六、查詢數據

查詢條件:conditioncondition格式參照模版,字段可爲空)

返回結果:answers(查詢結果形式[{……},{……},{……}]

Answer.find(condition, function(err,answers){

if (err) {

console.err(err);

}else{

           獲取answers,處理    

}// TODO handle err

})

 

第二種查詢方式

var query = Answer.find();

query

.where('age')

.gte(21)

……

.exec(callback);

 

七、修改數據

修改哪些數據的條件:conditioncondition格式參照模版,字段可爲空)

需修改爲的字段updatedata(格式參考模版,有的字段就修改,沒有的不修改)

Answer.update(condition, {

    $set: updatedata

}, {safe: false, multi: true}, function (err, numberAffected, raw) {

    if (err) return handleError(err);

    console.log('The number of updated documents was %d', numberAffected);

    console.log('The raw response from Mongo was ', raw);

});

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章