美文网首页
Node.js结合Mongodb

Node.js结合Mongodb

作者: 尤雨溪的大迷弟 | 来源:发表于2019-06-25 22:03 被阅读0次

1.安装mongoose

npm i mongoose -S
cnpm i mongoose -S //淘宝npm镜像,网速更快些

2.连接数据库

新建一个db.js文件

//连接数据库

const mongoose = require("mongoose");//引入mongoose模块
const DB_URL = "mongodb://127.0.0.1:27017/NBAteam";//连接数据库时,在终端中可看到连接路径(如下附图)

//userNewUrlParser这个属性会在url里识别验证用户所需的db
// mongoose.connect(DB_URL);//不加会提示警告
mongoose.connect(DB_URL,{ useNewUrlParser: true });

//监听数据库连接情况,便于观察
mongoose.connection.on("connected",()=> {
    console.log("数据库连接成功");
})
mongoose.connection.on("disconnected",()=> {
    console.log("数据库连接失败");
})
mongoose.connection.on("error",()=> {
    console.log("数据库连接错误");
})

//模块化开发思想:暴露mongoose模块(此时mongoose为自定义模块)
module.exports = mongoose;
QQ图片20190625215324.png

首先确保数据库连接池是打开的,如果未打开,请参照***,然后运行 node db.js 指令,发现打印出了 ‘数据库已经连接成功’ 字样,即数据库连接完成!

3.设计用户数据表---暴露了数据模型,并且在数据库中创建了集合

TIPS:
mongoose.model('User', UserSchema); 就会创建users集合
mongoose.model('Product',ProductSchema); 就会创建products集合
mongoose.model('MyBanner', BannerSchema); 就会创建mybanners集合

//设计用户数据表--暴露数据模型,并且在数据库中创建集合

const mongoose = require("./db");  //模块引入,后缀名可以省略 "./db.js"
// const Schema = mongoose.Schema;//数据库的集合对象
const { Schema } = mongoose; //es6写法:解构赋值

// 确定了一个数据集合有哪些字段以及字段的数据类型(具体还是以添加和修改时为准)
const userschema = new Schema({
    username:{ type : String },
    password:{ type : String },
    age:{ type : Number },
    tel:{ type : String },
    sex:{ type : String },
    lesson:{ type : String },
    city:{ type : String },
});
//创建一个集合并且将它暴露出去,供其他人增删改查
//会在数据库中创建出一个users的集合,与mongoose.model()的第一个参数有关
module.exports = mongoose.model("User",userschema);
// mongoose.model('User', UserSchema); 就会创建users集合
// mongoose.model('Product',ProductSchema); 就会创建products集合
// mongoose.model('MyBanner', BannerSchema); 就会创建mybanners集合

集合创建完成,可在终端中查看是否存在。

4.增删改查操作

4.1增

第一种方法:

 const User = require("./user");

//创建需要插入的数据 ---只能插入单条数据
const user = new User({
    username: "拉塞尔·威斯布鲁克",
    password:"000000",
    age:30,
    tel:"13815621254",
    sex:"男",
    lesson:"僵尸跳投",
    city:"俄克拉荷马",
});

user.save((err)=> {
    if (err) {
        console.log(err)
    } else {
        console.log("插入成功");
    }
})

第二种方法:

const User = require("./user");

User.insertMany([{
    username: "保罗·乔治",
    password: "131313",
    age: 28,
    tel: "15718565423",
    sex: "男",
    lesson: "全能战士",
    city: "俄克拉荷马",
}, {
    username: "卢卡·东契奇",
    password: "777777",
    age: 20,
    tel: "19978954321",
    sex: "男",
    lesson: "最佳新秀",
    city: "达拉斯",
},{
    username: "凯里·欧文",
    password: "111111",
    age: 27,
    tel: "19985236574",
    sex: "男",
    lesson: "德鲁大叔",
    city: "波士顿",
}],(err) => {
    if (err) throw err;// 抛出异常,不再继续执行后面的语句
    console.log("插入成功");
})

4.2改

const User = require("./user");

//修改一个
// User.updateOne({},{$set:{lesson:"超强的求胜欲"}},(err) => {
//     if (err) throw err;
//     console.log("更新成功");
// })
//修改带有条件的一个
// User.updateOne({username:"卢卡·东契奇"},{$set:{lesson:"超强的求胜欲"}},(err) => {
//     if (err) throw err;
//     console.log("更新成功");
// })
//age递增10
// User.update({username:"凯里·欧文"},{$inc:{ age:10 }},(err) => {
//     if (err) throw err;
//     console.log("更新成功");
// })
User.updateMany({},{$inc:{age:10}},(err) => {
    if (err) throw err;
    console.log("更新完成");
})

err的回调函数必须要有,否则无法对数据库进行修改。

4.3删

const User = require("./user");

User.deleteOne({lesson:"最佳新秀"}).exec((err) => {
    if (err) throw err;
    console.log("删除完成");
})

4.4查

第一个{}表示查询条件;第二个{}表示显示的字段

const User = require("./user");

//第一种写法:
// 所有数据
// User.find({},{},(err,data) => {
//     if (err) throw err;
//     console.log(data);
// });

//第二种写法:User后跟exec方法,回调函数写在exec方法中
//查询所有,只显示username和age
// User.find({},{ _id:0 ,username: 1,age :1}).exec((err,data) => {
//     if (err) throw err;
//     console.log(data);
// })

//查询所有,只显示username,age,tel,按照age递减来排序
// User.find({},{ _id:0, username:1, age:1, tel:1, }).sort({ age:-1 }).exec((err,data) => {
//     if (err) throw err;
//     console.log(data);
// })

// 查询tel中包含54的数据,只显示username,age,tel
// User.find({ tel:/54/},{ _id:0, username:1, age:1, tel:1}).exec((err,data) => {
//     if (err) throw err;
//     console.log(data);
// })

//查询age在27-28之间的数据($gte:27大于27且包含27;$lte:28小于28且包含28),只显示username,age
User.find({age: {$gte:27, $lte:28 }},{ _id:0, username:1, age:1}).exec((err,data) =>{
    if (err) throw err;
    console.log(data);
})

相关文章

网友评论

      本文标题:Node.js结合Mongodb

      本文链接:https://www.haomeiwen.com/subject/fhkfcctx.html