日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

mongoose的基本操作

發(fā)布時間:2025/3/20 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 mongoose的基本操作 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Mongoose庫簡而言之就是對node環(huán)境中MongoDB數(shù)據(jù)庫操作的封裝,通過操作javaScript對象來操作數(shù)據(jù)庫,代碼會顯得特別清晰。

一丶 ?npm install mongoose ?--save ? ?

下載Mongoose(其中包括了mongodb,不用重復Require)

二丶官網(wǎng)提供的hello模板

var mongoose = require('mongoose'); //引入mongoose mongoose.connect('mongodb://localhost/test'); // 連接數(shù)據(jù)庫var Cat = mongoose.model('Cat', { name: String }); // 創(chuàng)建一個Model模型 也就相當于創(chuàng)建了一個cats表var kitty = new Cat({ name: 'Zildjian' }); //實例化一個Model模型 ,相當于創(chuàng)建一個Kitty集合 kitty.save(function (err) { //save()方法,保存該對象,也就是向數(shù)據(jù)庫增加;if (err) {console.log(err);} else {console.log('meow');} });

 三丶mongoose的具體使用

   1,連接數(shù)據(jù)庫

var mongoose = require('mongoose'); //創(chuàng)建數(shù)據(jù)庫連接 var db=mongoose.createConnection('mongodb://127.0.0.1:27017/student'); //監(jiān)聽open事件 db.once('open', function (callback) {console.log("數(shù)據(jù)庫成功連接"); });

   ? ? 2丶定義模型

//創(chuàng)建了一個schema結構。 var studentSchema = new mongoose.Schema({name : {type : String},age : {type : Number}, });
var studentModel = db.model('Student', studentSchema);

  ? ? 3丶增

mongooseModel.create({name:'XiaoMIng',age:'18'}, function(error){if(error) {console.log(error);} else {console.log('成功添加小明同學信息');}// 關閉數(shù)據(jù)庫鏈接db.close(); });

   ? 4丶刪

mongooseModel.remove({name:'XiaoMing'}, function(error){if(error) {console.log(error);} else {console.log('成功刪除小明同學信息');
}//關閉數(shù)據(jù)庫鏈接db.close(); });

   ? 5丶改

var conditions = {name: 'XiaoMing'}; var update = {$set : {age : 27}}; var options = {}; mongooseModel.update(conditions, update, options, function(error){if(error) {console.log(error);} else {console.log('成功修改小明的的年齡');}//關閉數(shù)據(jù)庫鏈接 db.close(); });

? ? ? ? ? 6丶查

var select = {name: '小明'}; // 查詢條件
mongooseModel.find(select,function(error, result){if(error) {console.log(error);} else {console.log(result);}//關閉數(shù)據(jù)庫鏈接db.close(); });

  四丶自定義靜態(tài)方法

//自定義一個通過年齡查詢學生的方法
mongooseSchema.statics.findFromage = function(age, callback) {this.model('student').find({age: age}, callback); }
//通過年齡查詢所有學生信息
student.findFromage(
'30',function(err,result){console.log(result)})

?

轉載于:https://www.cnblogs.com/szyblogs/p/7286247.html

總結

以上是生活随笔為你收集整理的mongoose的基本操作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。