https://www.jianshu.com/p/7241f7c83f4a
启动mongodb是
mongod //
npm install mongodb --save //安装import mongodb from "mongodb" //引包
const MongoClient = mongodb.MongoClient;
const url = 'mongodb://localhost:27017/edu'; //edu数据库,没有会自动新建
MongoClient.connect(url, {useNewUrlParser:true}, (err, db) => {
if (err) {}
//操作数据库 //注意这里是3.x的APi 和2.X的不一样
db.db('edu').collection('adverts')
.insertOne(req.body, (err, result) => {
if(err){}
res.json({
success: true
})
})
//关闭连接
db.close();
});
mongoose:封装好的mongodb
1. 安装
npm install mongoose
2.
// import mongoose from 'mongoose';
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/student');
const studentSchema = mongoose.Schema({
name: String,
age: Number
});
const Student = mongoose.model('Student', studentSchema);
const s1 = new Student({
name: 'jack',
age: 18
});
s1.save( (err, result) => {
console.log(result);
});
来源:https://www.cnblogs.com/flyerya/p/11415648.html