初始化项目:cnpm init -y
局部安装mongoose:cnpm install mongoose -S
打开服务:mongod --dbpath d:datadb
const mongoose = require("mongoose");
const data_url = "mongodb://127.0.0.1:27017/bk1910";//定义数据库地址
mongoose.connect(data_url,(err,client)=>{
if(err){
console.log("连接失败")
}else{
console.log("连接成功")
}
})
//连接表并定义字段
const Users = mongoose.model("user",{
name:String,
age:String,
sex:String
})
const users = new Users({
name:"胡歌",
age:26,
sex:"男"
})
//添加数据
users.save().then((result)=>{
console.log(result)
})
//删除数据
Users.remove({"name":"胡歌"}).then((result)=>{
console.log(result)
})
//修改数据
Users.update({“name”:"胡歌"},{$set:{"name":"江疏影"}})then((result)=>{
console.log(result)
})
//查询数据
Users.find().then((result)=>{
console.log(result)
})