• mongoose操作笔记


    一、mongoose文档地址:

      https://cn.mongoosedoc.top/docs/api.html#update_update

      https://www.cnblogs.com/web-fengmin/p/6435681.html

    二、mongoose连接数据库

    var mongoose = require('mongoose');
    mongoose.connect('mongodb://localhost/studentmange', {
      autoIndex: false,
      useNewUrlParser: true
    })
    mongoose.set('useCreateIndex', true);
    
    var db = mongoose.connection
    db.once('open', function(callback) {
      console.log('数据库链接成功');
    })
    
    module.exports = db

    三、定义schema和创建实例对象(可以用new或者create两种方法)

    var mongoose = require('mongoose');
    
    var courseSchema = new mongoose.Schema({
      "cid": Number,
      "name": String,
      "students": [Number]
    })
    
    courseSchema.index({"cid": 1})
    
    courseSchema.statics.addStudent = function(courses, sid, callback) {
      console.log('插入课程开始', courses, sid)
      for(var i=0; i< courses.length; i++) {
        Course.update({"cid": courses[i]}, {$push: {"student": sid}}, function() {
          console.log('课程添加报名成功')
        })
      }
    }
    
    var Course = mongoose.model('Course', courseSchema)
    
    var course1 = new Course({
      "cid": 1,
      "name": "地理",
      "students": []
    })
    course1.save()
    
    Course.create({"cid": 2,
      "name": "数学",
      "students": []
    })
    
    module.exports = Course

    四、结合node.js做CURD 和 DAO层的封装

    exports.add = function(req, res, next) {
      Student.create(req.query, function() {
        console.log('插入学生成功')
        res.send('success')
        Course.addStudent(req.query.courses, req.query.sid, function() {
          console.log('插入课程成功');
        })
      })
    }
    
    exports.getAll = function(req, res, next) {
      Student.find({}, function(err, result) {
        res.send(result)
      })
    }
    
    exports.query = function(req, res, next) {
      Student.findOne({"sid": req.query.sid}, function(err, result) {
        console.log(result, 'query')
        res.send(result)
      })
    }
    
    exports.edit = function(req, res, next) {
      console.log('更新 id ', req.query.sid)
      Student.update({"sid": req.query.sid},{ $set: req.query}, function(err) {
        res.send('修改成功')
      })
    }
    
    exports.remove = function(req, res, next) {
      console.log('删除 id '+ req.query.sid)
      Student.remove({"sid": req.query.sid}, function(err) {
        res.send('删除成功')
      })
    }

    五、常用的操作运算符:

      $set $lt $gt $push $pull

     ===end 替他具体的细节看文档吧===

  • 相关阅读:
    linux安装nodejs
    Ubuntu下配置TFTP服务以及 android下使用TFTP
    笔记-《数据通信与网络教程》-第一章
    X86汇编基础-《Linux内核分析》云课堂笔记
    文章点击量排行TOP100-IBM power8算法挑战赛第三期
    LeetCode:Climbing Stairs
    LeetCode:Search for a Range
    LeetCode:Longest Substring Without Repeating Characters
    LeetCode:Linked List Cycle II
    LeetCode:Merge Sorted Array
  • 原文地址:https://www.cnblogs.com/angelatian/p/11066181.html
Copyright © 2020-2023  润新知