構(gòu)建Wep App 2018(四)|構(gòu)建數(shù)據(jù)庫(kù)連接|MongoDB+Vue+Express

connectMongo.js

const mongoose = require("mongoose");

function MongoConnection() {
  this.init = function() {
    console.log(
      "-------------------------------------------------------------------------"
    );
    console.log("[Mongo DB Connection initiating]");
    mongoose.connect("mongodb://news_admin:news_key@localhost/dbNews");
    this.db = mongoose.connection;
    this.db.on("error", console.error.bind(console, "[Connecting Failed]"));
    this.db.once("open", callback => {
      console.log("[Connected to Mongo DB]");
    });

    var newSchema = new mongoose.Schema({
      title: { type: String },
      content: { type: String },
      imgpath: { type: String },
      kind: { type: String },
      time: { type: Date, default: Date.now }
    });

    this.News = mongoose.model("News", newSchema);
  };

  this.SaveNews = function(title_, content_, kind_, imgpath_) {
    const news_tmp = new this.News({
      title: title_,
      content: content_,
      kind: kind_,
      imgpath: imgpath_
    });
    news_tmp.save().then(() => console.log("[Save News]", news_tmp));
  };

  this.FindNew = function(newskind) {
    this.News.find({ kind: newskind }, function(err, newsbykind) {
      console.log("[Find News]"+newsbykind);
      return newsbykind;
    });
  };
}

module.exports = { MongoConnection };
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容