Node中操作MongoDB

const mongoose = require('mongoose');

//连接数据库
mongoose.connect('mongodb://localhost/test',{useNewUrlParser: true, useUnifiedTopology: true});

const Schema = mongoose.Schema;

const UserSchema = new Schema({
  username: {
    type: String,
    required: true
  },
  password:{
    type: String,
    required: true
  },
  email:{
    type: String,
    required: true
  }
})

//创建集合的规范。(之后就操作这个集合)
const User = mongoose.model('User',UserSchema)

//增
const Result = new User({"username":'崔明',"password": "123456","email": "[email protected]"});

Result.save().then(err =>{console.log(err)
},res => {console.log('写入成功')
})


//删 deleteOne() deleteMany()
User.deleteMany({email: "[email protected]"}).then(err =>{console.log(err)
},res => {console.log(res)})


//改 UpdateOne() UpdateMany() findByIdAndUpdate()   One可以代替ById
User.findByIdAndUpdate("5ec5d640177ab811e8067b5f",{
  password: "159357"
}).then(err =>{console.log(err)
},res => {console.log('写入成功')
})


//查 find({条件...}) findOne({条件...}) Or查询:find({ $or: [ {条件},{条件} ] })
User.find({username: "崔明"}).then(err =>{console.log(err)
},res => {console.log(res)})

你可能感兴趣的:(Node中操作MongoDB)