构建Wep App 2018(四)|构建数据库连接|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 };

你可能感兴趣的:(构建Wep App 2018(四)|构建数据库连接|MongoDB+Vue+Express)