• Node操作MongoDb


    生产package.json文件

    npm init -y

    安装需要用到的包

    npm i mongoose

    实现一个简单的插入操作

    var mongoose = require('mongoose')
    //连接数据库
    mongoose.connect('mongodb://localhost/spitdb')
    var Schema = mongoose.Schema
    //创建文档结构
    var userSchema = new Schema({
        username:  String,
        password: String,
        sex:   String
      });
      //将文档结构发布为模型  第一个参数为集合名称,User会转成users
      var User = mongoose.model('User',userSchema)
      //保存
     var admin = new User({
         username:'admin',
         password:'123',
         sex:'男'
     })
     admin.save(function (err,result) {
         if(err){
             console.log('保存失败');
         } else{
            console.log('保存成功');
            //打印插入成功后的数据
            console.log(result);
         }
     })

    查询全部数据

    var mongoose = require('mongoose')
    //连接数据库
    mongoose.connect('mongodb://localhost/spitdb')
    var Schema = mongoose.Schema
    
    var userSchema = new Schema({
        username:  String,
        password: String,
        sex:   String
      });
    
      var User = mongoose.model('User',userSchema)
    
      User.find(function (err,data) {
          console.log(data);
          
      })

    按条件查询一个

    var mongoose = require('mongoose')
    //连接数据库
    mongoose.connect('mongodb://localhost/spitdb')
    var Schema = mongoose.Schema
    
    var userSchema = new Schema({
        username:  String,
        password: String,
        sex:   String
      });
    
      var User = mongoose.model('User',userSchema)
    
      User.findOne({username:'lyf'},function (err,data) {
          console.log(data);
          
      })

    按条件查询所有

    var mongoose = require('mongoose')
    //连接数据库
    mongoose.connect('mongodb://localhost/spitdb')
    var Schema = mongoose.Schema
    
    var userSchema = new Schema({
        username:  String,
        password: String,
        sex:   String
      });
    
      var User = mongoose.model('User',userSchema)
    
      User.find({sex:'男'},function (err,data) {
          console.log(data);
          
      })
  • 相关阅读:
    Cookies的实际存储位置
    搭建Git本地服务器
    在Tomcat中部署war
    Server.xml配置解析
    Tomcat配置详解,配置文件server.xml详解
    将centos7打造成桌面系统
    英语词汇大全
    商场/超市常见英语标识
    商务英语词汇大全
    常用繁体字大全
  • 原文地址:https://www.cnblogs.com/a-small-lyf/p/10771833.html
Copyright © 2020-2023  润新知