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);
      
  })

 

posted @ 2019-04-25 23:25  不爱笑青年  阅读(805)  评论(0编辑  收藏  举报