初始化項目:cnpm init -ymongodb
局部安裝mongoose:cnpm install mongoose -S數據庫
打開服務:mongod --dbpath d:\data\dbnpm
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)
})