MongoDB数据库的连接与操作
1、mongoose操作MongoDB数据库
const mongoose = require("mongoose")
mongoose.connect('mongodb://localhost/bidding-system')
let db = mongoose.connection
db.on('error', console.error.bind(console, 'connection error:'))
db.once('open', () => {
console.log("数据库连接成功")
});
let userSchema = new mongoose.Schema({
username: { type: String, require: true },
password: { type: String, require: true }
});
let userModel = mongoose.model('users', userSchema);
userModel.insertMany({
username:"张依依",password:"123456"
}).then(msg=>{
console.log("插入数据成功",msg)
}).catch(err=>{
console.log("插入数据失败",err)
})
2、nodeJs操作MongoDB
const mongoClient = require("mongodb").MongoClient;
const sql_url = "mongodb://localhost:27017/";
const db_name = "bidding-system";
mongoClient.connect(sql_url + db_name, {useNewUrlParser: true}, function (err, client) {
if (err) {
console.log("mongodb数据库连接失败!" + err);
return false;
}
console.log("mongodb数据库连接成功!");
global.getDB = () => {
return client.db(db_name)
}
});
module.exports = mongoClient;