mongoose學習筆記2--增刪改查1

查詢

以前咱們的集合已經建立成功,咱們就先來進行第一步操做 —— 查詢。javascript

查詢分不少種類型,如條件查詢,過濾查詢等等,今天只學習了最基本的find查詢。java

舉例數據庫

1.find查詢: obj.find(查詢條件,callback);數組

Model.find({},function(error,docs){
//若沒有向find傳遞參數,默認的是顯示全部文檔
});
 
Model.find({ "age": 28 }, function (error, docs) {
if(error){
console.log("error :" + error);
}else{
console.log(docs); //docs: age爲28的全部文檔
}
});

Model保存方法

Model提供了一個create方法來對數據進行保存。下面咱們來看一下示例:學習

1. Model.create(文檔數據, callback))對象

Model.create({ name:"model_create", age:26}, function(error,doc){
if(error) {
console.log(error);
} else {
console.log(doc);
}
});

  

entity保存方法

剛剛學習了model的create方法,那接下來就開始學習基於entity的保存方法吧。以下示例:blog

1. Entity.save(文檔數據, callback))ip

var Entity = new Model({name:"entity_save",age: 27});
 
Entity.save(function(error,doc) {
if(error) {
console.log(error);
} else {
console.log(doc);
}
});

  

數據更新

學習了數據的保存,接下來咱們就開始學習對數據的更新吧!rem

1.示例:obj.update(查詢條件,更新對象,callback);文檔

var conditions = {name : 'test_update'};
 
var update = {$set : { age : 16 }};
 
TestModel.update(conditions, update, function(error){
if(error) {
console.log(error);
} else {
console.log('Update success!');
}
});

  

刪除數據

有了數據的保存、更新,就差刪除了,下面咱們就來學習它吧!

1.示例:obj.remove(查詢條件,callback);

var conditions = { name: 'tom' };
 
TestModel.remove(conditions, function(error){
if(error) {
console.log(error);
} else {
console.log('Delete success!');
}
});

  

課程小結

本章咱們講述了針對數據庫的幾個操做方法,經過調用相關方法來對數據進行改變,無論是新增、刪除、修改仍是查查詢,你均可以辦到。

簡單回顧:

1. 查詢:find查詢返回符合條件一個、多個或者空數組文檔結果。

2. 保存:model調用create方法,entity調用的save方法。

3. 更新:obj.update(查詢條件,更新對象,callback),根據條件更新相關數據。

4. 刪除:obj.remove(查詢條件,callback),根據條件刪除相關數據。

相關文章
相關標籤/搜索