mongose鏈接數據庫與批插入

1.數據庫鏈接

最近在寫爬蟲程序進行抓包,使用mongodb數據庫的過程中遇到數據庫鏈接的問題。

因爲習慣了以前使用mysql時關閉數據庫鏈接的習慣,不太瞭解Mongodb如何操作數據庫鏈接。

加上我使用的是mongooes這個NPM模塊進行數據庫操作。

官方的示例是使用

var M = require('mongoose');
M.connect('mongodb://admin:[email protected]:10043/blog');

類似這樣的代碼段

但是例如當我在User.js 和Diary.js中都加人對應代碼,就發現會報數據庫鏈接錯誤。

查閱資料後,在stackoverflow發現,mogoooes對應一個數據庫只要進行一次鏈接,對應多個數據庫才需要進行多次鏈接

最終的解決方案是新建一個db.js,導出數據庫鏈接,每次需要就require這個模塊

var M = require('mongoose');
M.connect('mongodb://admin:[email protected]:10043/blog');
// reference to the database connection 爲這個連接創建一個引用
var db = M.connection;
// expose to modules that require database.js 把這個引用暴露給引用 database 模塊的其他模塊
module.exports = db;
2.批插入

mongodb有個批插入的功能,使用mongooes後也想實現,最後查閱文檔總算成功了

這裏附一個完整的Model

/**
 * Created by Administrator on 14-8-8.
 */
var mongoose = require('mongoose');
var db = require('./db.js');
var gooditemSchema = new mongoose.Schema({
    iid:String,
    status: String,
    date: String,
    pv: String,
    url : String,
    name :String,
    owner :String

}, {
    collection: 'gooditems'
});

var GooditemModel = mongoose.model('Gooditem', gooditemSchema);

function Gooditem(gooditem) {
    this.iid=gooditem.iid;
    this.name = gooditem.name;
    this.pv =gooditem.pv;
    this.status = gooditem.status;
    this.url = gooditem.url;
    this.date = gooditem.date;
    this.owner = gooditem.owner;
};
//保存
Gooditem.prototype.save = function(callback) {
    var gooditem= {
        iid:this.iid,
        name:this.name,
        pv :this.pv,
        status : this.status,
        url : this.url,
        date : this.date,
        owner : this.owner
    };

var Model = new GooditemModel(gooditem);
     Model.save(function (err, gooditem) {
        if (err) {
            return callback(err);
        }
        callback(null, gooditem);

    });
};
//查
Gooditem.get = function(iid, callback) {
    gooditemModel.findOne({iid: iid}, function (err, gooditem) {
        if (err) {
            return callback(err);
        }
        callback(null, gooditem);
    });
};
//改
Gooditem.update = function(iid,img,callback){
    var conditions = {iid : iid};
    var update     = {$set : {img: img}};
    var options    = {upsert : true};
    gooditemModel.update(conditions, update, options, function(error,data){
        if(error) {
            console.log(error);
        } else {
            callback( 'update ok!');
        }
    });

}
//批插入
Gooditem.batch = function(array,callback){
    GooditemModel.create(array,function(err){
        if(err){
            callback('error')
        }
        else{
            callback("ok")
        }
    })

}
module.exports = Gooditem;



發佈了24 篇原創文章 · 獲贊 1 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章