Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
return new Promise(async (resolve, reject) => {
mongoose.connection
.on('error', error => reject(error))
.on('close', () => console.log(`[${'!'.red}]Database connection closed`))
.once('open', () => resolve(mongoose.connections[0]))
try {
await mongoose.connect(uri)
} catch (error) {
reject(error)
}
// Gracefully shutdown when INTERRUPT signal occurred
process.on('SIGINT', () => mongoose.connection.close(() => process.exit(0)))
})
// create one place for db connection
// Bring Mongoose into the app
const mongoose = require('mongoose');
// Build the connection string
// const dbURI = 'mongodb://localhost:27017/votingapp';
const dbURI = process.env.MONGOLAB_URI;
mongoose.Promise = global.Promise;
// Create the database connection
mongoose.connect(dbURI, { useMongoClient: true });
// CONNECTION EVENTS
// When successfully connected
mongoose.connection.on('connected', () => {
console.log(`Mongoose default connection open to ${dbURI}`);
});
// If the connection throws an error
mongoose.connection.on('error', (err) => {
console.log(`Mongoose default connection error: ${err}`);
});
// When the connection is disconnected
mongoose.connection.on('disconnected', () => {
console.log('Mongoose default connection disconnected');
});
// If the Node process ends, close the Mongoose connection
process.on('SIGINT', () => {
mongoose.connection.close(() => {
const bodyParser = require('body-parser');
const path = require('path');
require('dotenv').config();
const articles = require('./routes/articlesRoute.js');
const users = require('./routes/usersRoute.js');
const config = require('./config.js');
const MONGODB_URI = config.mongodburi || 'mongodb://localhost:27017/basic-mern-app';
const PORT = process.env.PORT || 5000;
mongoose.connect(MONGODB_URI, { useNewUrlParser: true });
mongoose.connection.on('connected', () => {
console.log('Connected to MongoDB');
});
mongoose.connection.on('error', (error) => {
console.log(error);
});
let app = express();
// Body Parser Middleware
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'client/build')));
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
if (req.method === 'OPTIONS') {
res.header("Access-Control-Allow-Methods", "PUT, POST, DELETE, GET");
const express = require('express')
const mongoose = require('mongoose')
//链接mongodeb
const DB_URL = 'mongodb://127.0.0.1:27017/test'
mongoose.connect(DB_URL)
mongoose.connection.on('connected',function () {
console.log('mongo connnect success');
})
//类似于mysql的表 mongo里有文档、字段的概念
const User = mongoose.model('user', new mongoose.Schema({
user:{type:String,require:true},
age:{type:Number,require:true}
}))
//新增数据
// User.create({
// user:'zhangjianan',
// age:21
// },function (err,doc) {
// if (!err) {
// console.log(doc);
// }else{
// console.log(err);
app.set('views', config.root + '/server/views');
app.set('view engine', 'jade');
app.use(compression());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(cookieParser());
app.use(passport.initialize());
// Persist sessions with mongoStore
// We need to enable sessions for passport twitter because its an oauth 1.0 strategy
app.use(session({
secret: config.secrets.session,
resave: true,
saveUninitialized: true,
store: new mongoStore({ mongoose_connection: mongoose.connection })
}));
if ('production' === env) {
// app.use(favicon(path.join(config.root, 'public', 'favicon.ico')));
app.use(express.static(path.join(config.root, 'public')));
app.set('appPath', path.join(config.root, 'public'));
app.set('appAppPath', path.join(config.root, 'public', 'app'));
app.set('adminPath', path.join(config.root, 'public', 'admin/'));
app.set('themesFolder', path.join(config.root, 'public', 'themes', '/'));
app.set('extensionsFolder', path.join(config.root, 'public', 'extensions', '/'));
app.set('frontEnd', 'public');
app.use(morgan('dev'));
}
if ('development' === env || 'test' === env) {
app.use(require('connect-livereload')());
module.exports = (dbConnectionString) => {
if (!dbConnectionString) {
throw new Error('add correct format of config with dbConnectionString');
}
const options = {
useMongoClient: true,
promiseLibrary: require('bluebird'),
};
// Check for errors on connecting to Mongo DB
mongoose.connection.on('error', (err) => {
logging.error(`Error! DB Connection failed. Error: ${err}`);
return err;
});
// Connection opened successfully
mongoose.connection.once('open', () => {
logging.info('Connection to MongoDB established');
});
mongoose.connection.on('disconnected', () => {
logging.info('Connection to MongoDB closed');
logging.info('-------------------');
});
return {
getConnection() {
after((done) => {
mongoose.models = {};
mongoose.modelSchemas = {};
mongoose.connection.close(() => done());
});
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/invoiceDB');
//schema for area
var productSchema = mongoose.Schema({
id: String,
name: {type: String, unique: true, dropDups: true},
rate: Number,
description: String,
status: Boolean,
vat: String
});
var Product = mongoose.model('product', productSchema);
var db = mongoose.connection;
db.on('error', function () {
console.log('error in connection');
});
db.once('open', function () {
var data_array = [
new Product({name: '256Kbps', rate: 500, description: '', status: true, vat: '10'}),
new Product({name: '512Kbps', rate: 600, description: '', status: true, vat: '10'}),
new Product({name: '1Mbps', rate: 1000, description: '', status: true, vat: '10'}),
new Product({name: '2Mbps', rate: 2000, description: '', status: true, vat: '10'}),
new Product({name: '3Mbps', rate: 3000, description: '', status: true, vat: '10'}),
new Product({name: '3Mbps', rate: 3000, description: '', status: true, vat: '10'}),
new Product({name: '4Mbps', rate: 4000, description: '', status: true, vat: '10'}),
new Product({name: '5Mbps', rate: 5000, description: '', status: true, vat: '10'})
];
api.getOrionEE().on("close-server", function() {
logger.info("Closing MongoDB");
if (mongoose && (mongoose.connection.readyState === 1 || mongoose.connection.readyState === 2)) {
mongoose.disconnect();
}
});
}
after(async () => {
await mongoose.connection.close();
});
beforeEach(async () => {