美文网首页我爱编程
构建Wep App 2018(四)|构建数据库连接|MongoD

构建Wep App 2018(四)|构建数据库连接|MongoD

作者: 绍重先 | 来源:发表于2018-04-11 22:59 被阅读0次

    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(四)|构建数据库连接|MongoD

        本文链接:https://www.haomeiwen.com/subject/stdtkftx.html