1、先进行打包管理操作下载mongoose模块,具体操作见nodejs打包管理步骤_weixin_43930256的博客-优快云博客
2、node.js导入mongoose模块。
// 导入mongoose模块
let mongoose = require("mongoose");
3、打开mongodb,点击+号创建一个数据库。
4、node.js 连接数据库,此处Shop是第三步中创建的数据库名。
// 链接数据库
mongoose.connect('mongodb://localhost/Shop').
then(r => {//主要用于测试连接是否成功,确认成功后then和catch可以不用写
// 进入then说明链接成功
console.log("链接数据库成功");
}).catch(r => {
// 进入catch说明链接失败
console.log("链接数据库失败");
})
5、node.js在数据库Shop中创建表结构
// 创建表结构
let goods_Schema = mongoose.Schema({//结构中内容可按照这种格式自定义
goodsId: Number,
goodsName: String,
googsPrice: Number,
isTejia: Boolean,
goodsgift: [String]
})
6、node.js用表结构创建表。
// 用表结构创建表
let Goods = mongoose.model("goods", goods_Schema);
7、node.js代码添加数据两种方式,第二种更方便,不需要调用且可以一次添加多条数据。
// // 向表中添加数据第1种方式
let g1 = new Goods(
{
"goodsId":1,
"goodsName":"华为mate",
"googsPrice":8899,
"isTejia":false,
"goodsgift":["手机壳","钢化膜","蓝牙耳机"]
}
)
// 将商品的实例保存在表中
g1.save();
// 创建表、添加数据第2种方式
Goods.create([
{
"goodsId": 2,
"goodsName": "华为note",
"googsPrice": 7899,
"isTejia": false,
"goodsgift": ["手机壳", "钢化膜", "充电头"]
},
{
"goodsId": 3,
"goodsName": "vivo3",
"googsPrice": 2399,
"isTejia": true,
"goodsgift": ["手机壳", "钢化膜", "有线耳机"]
},
{
"goodsId": 4,
"goodsName": "oppo手机",
"googsPrice": 1999,
"isTejia": false,
"goodsgift": ["手机壳"]
},
{
"goodsId": 5,
"goodsName": "realme手机",
"googsPrice": 1899,
"isTejia": false,
"goodsgift": ["钢化膜"]
}
]).then(r=>{
console.log(r);
console.log("添加成功");
})
8、node.js代码删除符合条件数据的两种方式,then主要用于测试是否成功。
// 删除一条数据
Goods.deleteOne({"goodsId":2}).then(r=>{
console.log("删除条数"+r.deletedCount);
})
// 删除多条数据
Goods.deleteMany({"goodsName":"小米手机"}).then(r => {
console.log(r);
})
9、node.js代码修改符合条件数据的两种方式,注意参数写法。
// 修改操作
// 修改一条 updateOne("条件","修改值")
Goods.updateOne({"goodsId":2},{"goodsName":"华为手机","googsPrice":1234}).then(r=>{
console.log(r);
})
// 修改多条
Goods.updateMany({"goodsName":"oppo手机"},{"googsPrice":2999}).then(r=>{
console.log(r);
})
10、node.js代码查询符合条件数据的两种方式。
// 查询符合条件的一条或多条记录
Goods.find({"goodsName":"华为手机"}).then(r=>{
console.log(r);
})
// 查询指定列的内容
Goods.find().select("goodsId goodsName").then(r=>{
console.log(r);
})
11、代码写完后,点击终端新建终端,在终端进入当前文件所在位置,执行node 当前文件名运行代码。看返回的测试结果,成功则到mongodb那边刷新查看数据。
注意:then和catch主要用于测试确认代码操作是否成功;
为了看到效果,增删改查最好写到不同的文件去执行,此时每个文件都需要做步骤2、4、5、6。