1.原生连接数据库
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("dumall");
dbo.collection("goods"). find({}).toArray(function(err, result) { // 返回集合中所有数据
if (err) throw err;
console.log(result);
db.close();
res.json({
result:{
count:result.length,
list:result}
});
});
});
2.mongoose连接数据库
schema运用:
var mongoose= require('mongoose');
var Schema= mongoose.Schema;
var productSchema= new Schema({
productId:{type:String},
productName:String,
salePrice:Number,
productImage:String,
productUrl:String
});
module.exports= mongoose.model('Good',productSchema);
连接数据库
var mongoose= require('mongoose');
var Goods = require('../models/goods');
mongoose.connect('mongodb://127.0.0.1:27017/dumall', { useNewUrlParser:true });
mongoose.connection.on("connected",function () {
console.log("mongoDB coennected success.")
});
mongoose.connection.on("error",function () {
console.log("mongoDB coennected fail.")
});
mongoose.connection.on("disconnected",function () {
console.log("mongoDB coennected disconnected.")
});
Goods.find({},function(err,doc){
if (err) {
res.json({
status:'1',
msg:err.message
});
}else{
res.json({
status:'0',
msg:'',
result:{
count:doc.length,
list:doc
}
})
}
})