zoukankan      html  css  js  c++  java
  • mongoose系列——几行代码实现CRUD

    1. nodejs 确实好用,mongoose封装了mongodb,代码很简洁。

    const mongoose = require('mongoose');
    
    mongoose.connect("mongodb://localhost/xinliao");
    
    var Workshop = mongoose.model('Workshop', new mongoose.Schema({test: String}));
    Workshop.find({}).exec((err, resp) => {
        console.log(resp);
    })
    
    data = new Workshop({
        test: 'safasdfa111111'
    })
    data.save((err, resp) => {
        console.log(resp);
    })
    

      这几行代码就可以实现 查询,和插入功能了,确实方便。

     完整的代码如下:

     const mongoose = require('mongoose');
     mongoose.connect("mongodb://localhost/xinliao");
     
     var Workshop = mongoose.model('Workshop', new mongoose.Schema({zzz: String}));
     
     //read
     Workshop.find({}).exec((err, resp) => {
         console.log(resp);
     })
     
     //create
     new Workshop({
         zzz: 'ljl'
     }).save((err, res) => {
         console.log(res);
     })
     
     //update
     Workshop.find({_id: "5c3340d4ead83930960170f0"}).exec((err, res) => {
         console.log(res);
         if(res.length){
             res[0].zzz ="alias_ljl";
             res[0].save((err, res) => {
                 console.log('updadte success', res);
             })
     
         }
        })
     //delete
     Workshop.deleteOne({_id: "5c3340a1bf097c30727d9cfb"}).exec((err, res) => {
         console.log(res);
     });
    

      

  • 相关阅读:
    node学习报错之883
    vue-cli4创建项目
    Decorator学习笔记
    合天网安实验室学习笔记----Linux基础
    IDF实验室解题学习笔记1
    QA笑话----杂思
    测试优先
    Python的IDE:Eclipse+PyDev配置
    JS实现浏览器的title闪烁
    JSTL实现分页
  • 原文地址:https://www.cnblogs.com/oxspirt/p/10235284.html
Copyright © 2011-2022 走看看