• 用js代码操作数据库mogodb


    1.创建相关的数据库集合

    在 链接数据库的 命令行终端运行  

    >use sh2001                            //创建库

    switched to db sh2001

    >db.createCollection('products')       //创建所需聚合集

    { "ok" : 1 }

    >db.createCollection('users')

    { "ok" : 1 }

    db.createCollection('carts')

    { "ok" : 1 }

    db.createCollection('orders')

    { "ok" : 1 }

    db.createCollection('banners')

    { "ok" : 1 }

    db.createCollection('messages')

    { "ok" : 1 }

    db.createCollection('activitys')

    { "ok" : 1 }

    2.使用mongoose

    用node安装cnpm i mongoose -S

    2.1 链接数据库

    const mongoose = require('mongoose');                  //导入mongise模块
     ​
    const DB_URL = "mongodb://127.0.0.1:27017/sh2001"      //存放数据库的链接地址
    // 后面两个不需要记忆,会自动提示
    mongoose.connect(DB_URL, { useNewUrlParser: true, useUnifiedTopology: true });   //连接数据库
    //根据不同的结果响应不同的数据
    mongoose.connection.on('connected', () => {
      console.log('数据库链接成功')
    })
    ​
    mongoose.connection.on('disconnected', () => {
      console.log('数据库链接失败')
    })
    ​
    mongoose.connection.on('error', () => {
      console.log('数据库链接异常')
    })
    ​
    module.exports = mongoose;    //导出数据库连接的模板

    2.创建数据库集合

         

    新建文件夹和文件collection/Product.js
    
    const mongoose = require('./../db');导入刚刚建立的db连接数据库的操作
    ​
    const Schema = mongoose.Schema;    //创建模板并规定模板的有关类型  schema见前篇博客
    ​
    const productSchema = new Schema({
      proid: { type: String },
      proname: { type: String },
      probrand: { type: String },
      brandimg: { type: String },
      proimg: { type: Array },
      price: { type: Number },
      detail: { type: String },
      stock: { type: Number },
      sales: { type: Number }
    })
    ​
    // 就会自动创建一个  数据库集合products
    module.exports = mongoose.model('Product', productSchema);

    3.插入数据

    const Product = require('./../collection/Product')
    ​
    /**
     * 命令行
     * db.products.insertOne({})
     * db.products.insertMany([{}, {}])
     * db.products.insert([{}, {}])
     * 
     * 代码
     * db.products.insertMany([{}, {}])
     */
    ​
    Product.insertMany({
      proid: '1111',
      proname: 'Apple iPhone SE (A2298) 64GB 黑色 移动联通电信4G手机',
      probrand: 'iphone',
      brandimg: 'https://img10.360buyimg.com/imgzone/jfs/t17752/324/262367977/74875/fd9a74db/5a65c544N9fcaf6f7.png',
      proimg: [
        'https://img10.360buyimg.com/n1/s450x450_jfs/t1/96643/2/18618/145854/5e9738d5Ea3ddc9d9/694707618ef7b5cd.jpg',
        'https://img10.360buyimg.com/n1/s450x450_jfs/t1/98709/6/18653/102688/5e9738e3Ed573c9e4/6850f1a0c68bb4a7.jpg',
        'https://img10.360buyimg.com/n1/s450x450_jfs/t1/117670/38/1396/71194/5e9738e8E70c13df7/7b6d575c3001de7c.jpg'],
      price: 3199,
      detail: '详情描述',
      stock: 2000,
      sales: 100
    }, (err) => {
      // nodejs 的错误优先回调
      if (err) throw err;
      console.log('插入成功')
    })
    
    注意:插入时貌似只能用insertMany()
         插入多条数据时要用json数组的形势进行插入

    4.删除数据

     1 const Product = require('./../collection/Product')
     2  3 /**
     4  * 命令行 + 代码
     5  * product.deleteOne({key: value}) 单条
     6  * product.deleteMany({key: value}) 多条
     7  * product.deleteOne({}) 所有
     8  * 
     9  */
    10 11 // Product.deleteOne({ proid: '1111' }, (err) => {
    12 //   if (err) throw err;
    13 //   console.log('删除成功')
    14 // })
    15 16 // Product.deleteMany({ proid: '1111'}, (err) => {
    17 //   if (err) throw err;
    18 //   console.log('删除成功')
    19 // })
    20 21 Product.deleteMany({}, (err) => {
    22   if (err) throw err;
    23   console.log('删除成功')
    24 })
    25 5.修改数据
    26 const Product = require('./../collection/Product')
    27 28 /**
    29  * // 设置
    30  * Product.updateOne({key1: value1}, { $set: { key2: value2, key3: value3}})
    31  * Product.updateMany({key1: value1}, { $set: { key2: value2, key3: value3}})
    32  * Product.updateMany({}, { $set: { key2: value2, key3: value3}})
    33  * // 自增自减 num
    34  * Product.updateOne({key1: value1}, { $inc: { key2: num}})
    35  * Product.updateMany({key1: value1}, { $inc: { key2: num}})
    36  * Product.updateMany({}, { $inc: { key2: num}})
    37  * 
    38  */
    39 40 // 库存减一 销量加1
    41 Product.updateOne({proid: '1111'}, { $inc: { stock: -1, sales: 1}}, (err) => {
    42   if (err) throw err;
    43   console.log('修改成功')
    44 })

    6.查询数据

     1 const Product = require("./../collection/product")
     2 
     3 
     4 //查询语句也有很多种
     5 /**
     6  * 
     7  * 
     8  * 
     9  * 
    10  * 
    11  * 
    12  * 
    13 */
    14 
    15 
    16 //此查询时忽略其他只显示proname
    17 
    18 // Product.find({}, { _id: 0, proname: 1 }).exec((err, data) => {
    19 //     if (err) throw err;
    20 //     console.log(data)//打印查到的内容
    21 // })
    22 
    23 //除了id以外都打印
    24 // Product.find({}, { _id: 0 }).exec((err, data) => {
    25 //     if (err) throw err;
    26 //     console.log(data)//打印查到的内容
    27 // })
    28 
    29 
    30 //
    31 Product.find({}).exec((err, data) => {
    32     if (err) throw err;
    33     console.log(data)//打印查到的内容
    34 })

    6.修改数据

     1 const Product = require("./../collection/product")
     2 
     3 
     4 
     5 //修改的方法有很多种
     6 /** 
     7  * 
     8  * 
     9  * User.updateOne({username: '吴大勋'}, {$set: {age: 20}}, err => { if (err) throw err; console.log('修改成功') })
    10  * 
    11  * */  
    12 
    13 Product.updateOne({prodid:"1111"},{$set:{prodid:"2222"}},(err)=>{
    14     if(err) throw err;
    15     console.log('修改成功')
    16 })
  • 相关阅读:
    表单重复提交问题
    Win8.1卸载64位Oracle Database 11g的详细图文步骤记录
    A1084. Broken Keyboard (20)
    A1088. Rational Arithmetic (20)
    A1089. Insert or Merge (25)
    A1034. Head of a Gang (30)
    A1013. Battle Over Cities (25)
    A1030. Travel Plan (30)
    A1003. Emergency (25)
    A1076. Forwards on Weibo (30)
  • 原文地址:https://www.cnblogs.com/moluxi/p/13043770.html
Copyright © 2020-2023  润新知