当前位置: 首页>>代码示例>>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;未经允许,请勿转载。