當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript MongoClient.connect方法代碼示例

本文整理匯總了TypeScript中mongodb.MongoClient.connect方法的典型用法代碼示例。如果您正苦於以下問題:TypeScript MongoClient.connect方法的具體用法?TypeScript MongoClient.connect怎麽用?TypeScript MongoClient.connect使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在mongodb.MongoClient的用法示例。


在下文中一共展示了MongoClient.connect方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: function

MongoClient.connect("mongodb://localhost:27017/dragonoids", function(err: any, db: mongodb.Db) {
if (err)
	throw err

var Collections: {
	Users: mongodb.Collection;
	BlogPosts: mongodb.Collection;
	Tags: mongodb.Collection;
} = {
	Users: db.collection("users"),
	BlogPosts: db.collection("blog"),
	Tags: db.collection("tags")
};
console.info("Connected to MongoDB server");

var express = require("express");
var app = express();
// Express middleware
var serveStatic = require("serve-static");
var responseTime = require("response-time");
var compress = require("compression");
var bodyParser = require("body-parser").urlencoded({extended: false});
var session = require("express-session");
var MongoStore = require("connect-mongo")({session: session});

app.use(compress());
app.use(responseTime());
var secret: string = fs.readFileSync("secret.txt", {encoding: "utf8"});
app.use(session({
	secret: secret,
	cookie: {
		path: "/",
		httpOnly: true,
		maxAge: 3600000 * 24 * 7 * 4 // 1 month
	},
	store: new MongoStore({db: db}),
	resave: true,
	saveUninitialized: true
}));

app.set("views", __dirname + "/views");
app.set("view engine", "jade");
app.locals.pretty = true;

app.use("/css", serveStatic("css"));
app.use("/js", serveStatic("js"));
app.use("/img", serveStatic("img"));

// Check if logged in
app.use(function(request, response, next) {
	Collections.Users.findOne({"username": request.session["username"], "login.token": request.session["token"]}, function(err: Error, user: any): void {
		if (user) {
			response.locals.loggedIn = true;
			response.locals.user = user;
		}
		else {
			response.locals.loggedIn = false;
		}
		next();
	});
});

function createNonce (bytes: number = 32): string {
	return crypto.randomBytes(bytes).toString("hex");
}

app.route("/").get(function(request, response) {
	// Read the team file
	fs.readFile("team.json", {charset: "utf8"}, function(err: Error, team: string): void {
		if (err) {
			console.error(err);
			response.send(500, "Error reading team.json!");
			return;
		}
		try {
			var members: TeamMember[] = JSON.parse(team).members;
		} catch (e) {
			console.error(e);
			response.send(500, "Invalid team.json file!");
			return;
		}
		response.render("index", {members: members}, function(err: Error, html: string): void {
			if (err) {
				console.error(err);
				response.send(500, "A Jade error occurred!");
				return;
			}
			response.send(html);
		});
	});
});
app.route("/blog").get(function(request, response) {
	// Get blog posts
	var pinnedPostsCursor = Collections.BlogPosts.find({"pinned": true}).sort({"date": -1});
	var regularPostsCursor = Collections.BlogPosts.find({"pinned": false}).sort({"date": -1});
	pinnedPostsCursor.toArray(function(err, pinnedPosts) {
		regularPostsCursor.toArray(function(err2, regularPosts) {
			if (err || err2) {
				console.log(err, err2);
				response.send("A MongoDB error occurred");
//.........這裏部分代碼省略.........
開發者ID:petschekr,項目名稱:Dragonoids-Website,代碼行數:101,代碼來源:server.ts

示例2: connect

 /**
  * Initialises the connection to the MongoDB server
  */
 async connect() {
     this.client = await MongoClient.connect(this.config.url, this.config.options);
     this.db = this.client.db(this.config.dbName);
 }
開發者ID:RevFramework,項目名稱:rev-framework,代碼行數:7,代碼來源:backend.ts

示例3: model

        console.log("  --teams         number of teams to generate");
        console.log("  --racers-team   number of racers per team");
        console.log("  --mode          storage model (1 -> records per racer or 2 -> record per team)");
        console.log("  --ratio         ratio of updates to queries during the test");
        console.log("  --help          shows this message");
        process.exit();
    } else {
        console.log("Invalid Option: " + arg);
    }
});

console.log(`Threads: ${threadCount}, Teams: ${teams}, Racers/Team: ${racersATeam}, ` +
    `Mode: ${mode == 1 ? "RacerTable" : "TeamTable"}, Ratio: ${updateQueryRatio}, Accesses: ${accessCount}`);

// Open connection to database to create initial state
MongoClient.connect('mongodb://localhost:27017/' + (mode == DBMode.RacerTable ? 'racer' : 'team')).then((db:Db)=> {

    let col:Collection = db.collection('ski');
    
    // delete the collection and then repopulate it
    col.drop().catch(err => err).then(() => {
        console.log('Start DB Creation');
        console.time('Create DB');
        let completedCreation:Promise<any>;
        if (mode == DBMode.RacerTable) {
            
            let toAdd:Array<IndependentRacer> = new Array<IndependentRacer>();
            for (let team = 0; team < teams; ++team) {
                // generate team id
                let teamId = genId(team);
                for (let racer = 0; racer < racersATeam; ++racer) {
開發者ID:Tiedye,項目名稱:RazzieTest,代碼行數:31,代碼來源:index.ts

示例4: connect

function connect(callback: (err, db) => void ) {
    MongoClient.connect('mongodb://' + address, callback);
}
開發者ID:At-sushi,項目名稱:developersyp,代碼行數:3,代碼來源:database.ts

示例5:

 // Open Database
 callback => mongodb.MongoClient.connect("mongodb://10.0.75.2:27017/demo", callback),
開發者ID:HansenHo,項目名稱:Samples,代碼行數:2,代碼來源:app.ts

示例6: if

mongodb.MongoClient.connect("mongodb://10.0.75.2:27017/demo", (err, db) => {
    // Read all persons with first name "John"
    db.collection("Person", (err, coll) => {
        coll.find({ firstName: "John" }).toArray((err, res) => {
            // In order to close DB after we are done, we have to use a counter
            var counter = res.length;
            var closedb = () => { if (--counter == 0) db.close(); };

            // For each person
            for (var i = 0; i < res.length; i++) {
                var p = res[i];

                // If Person is customer
                if (p.isCustomer) {
                    // Read customer details for person
                    db.collection("Customer", (err, custColl) => {
                        custColl.findOne({ id: p.customerId }, (err, cust) => {
                            // Print person and customer details
                            console.log(`John ${p.lastName} works for ${cust.customerName}.`);

                            // Call helper function to close DB if done
                            closedb();
                        });
                    });
                } else {
                    // Read supplier details for person
                    db.collection("Supplier", (err, supplColl) => {
                        supplColl.findOne({ id: p.supplierId }, (err, suppl) => {
                            // Print person and supplier details
                            console.log(`John ${p.lastName} works for ${suppl.supplierName}.`);

                            // Call helper function to close DB if done
                            closedb();
                        });
                    });
                }
            }
        });
    });
});
開發者ID:HansenHo,項目名稱:Samples,代碼行數:40,代碼來源:app.ts

示例7: reject

 const db = await new Promise<mongo.Db>((resolve, reject) => 
     mongo.MongoClient.connect(mongoUri + '/auth', (err, result) => err ? 
         reject(`Could not connect to ${mongoUri}: ${err}`) : 
         resolve(result)));
開發者ID:Azure,項目名稱:azure-iot-library,代碼行數:4,代碼來源:authentication.ts

示例8: Application

import {Application} from './common/Application';
import {UserController} from './user/UserController';
import {GriddeController} from './user/GriddeController';
import * as mongodb from 'mongodb';

const port = 3002;
const app = new Application();
app.controller(UserController);
app.controller(GriddeController);
app.setPort(port);
app.setAppName('Listocity');

mongodb.MongoClient.connect('mongodb://localhost:27017/listocity')
    .then((db) => {
        app.addDataSource(db);
        app.start();
    }).catch((error) => {
    console.error("index.ts:15", error);
});

開發者ID:vsuhanov,項目名稱:listocity-server,代碼行數:19,代碼來源:index.ts

示例9: connect

  connect():void {
    MongoClient.connect(this.dbUrl, (err, conDb) => {
      this.connectHandler(err,conDb);
    });
 }
開發者ID:joergwasmeier,項目名稱:fabalous,代碼行數:5,代碼來源:FabaMongoConnection.ts

示例10: express

/// <reference path="typings/tsd.d.ts" />

import * as express from 'express'
import { MongoClient, Db } from 'mongodb'
import { createFilter } from 'odata-v4-mongodb'

const app = express()
const mongocn = process.env.MONGO_URL || "mongodb://localhost:27017/zeddb"

MongoClient
  .connect(mongocn)
  .then(db => startDataService(db))

function startDataService(db: Db) {
  app.get("/api/products", (req, res, next) => {
    let filter = createFilter(req.query.$filter || '')
    console.log("filtering products: " + JSON.stringify(filter))
    db.collection("products")
      .find(filter)
      .toArray()
      .then(products => res.json(products))
      .catch(next)
  })
  console.log("Data service started")
  return seedInitData(db)
}

function seedInitData(db:Db) {
  var products = db.collection("products")
  products.count({}).then( result => {
    if (!result) {
開發者ID:jaystack,項目名稱:odata-v4-server-example-ts,代碼行數:31,代碼來源:server.ts


注:本文中的mongodb.MongoClient.connect方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。