1 var mongoose = require('mongoose') 2 3 var Schema = mongoose.Schema 4 5 // 1. 链接数据库 6 // 指定链接的数据库不须要存在,当你插入第一条数据以后就会自动被建立出来 7 mongoose.connect('mongodb://localhost/itcast') 8 9 // 2. 设计文档结构(表结构) 10 // 字段名称就是表结构中的属性名称 11 // 约束的目的是为了保证数据的完整性,不要有脏数据 12 var userSchema = new Schema({ 13 14 username: { 15 type: String, 16 required: true // 必须有 17 }, 18 password: { 19 type: String, 20 required: true 21 }, 22 email: { 23 type: String 24 } 25 }) 26 27 // 3. 将文档结构发布为模型 28 // mongoose.model 方法就是用来将一个架构发布为 model 29 // 第一个参数:传入一个大写名词单数字符串用来表示你的数据库名称 30 // mongoose 会自动将大写名词的字符串生成 小写复数 的集合名称 31 // 例如这里的 User 最终会变为 users 集合名称 32 // 第二个参数:架构 Schema 33 // 34 // 返回值:模型构造函数 35 var User = mongoose.model('User', userSchema)
1 var admin = new User({ 2 username: 'zs', 3 password: '123456', 4 email: 'admin@admin.com' 5 }) 6 7 admin.save(function (err, ret) { 8 if (err) { 9 console.log('保存失败') 10 } else { 11 console.log('保存成功') 12 console.log(ret) 13 } 14 })
1 // 查询所有数据 2 User.find(function (err, ret) { 3 if (err) { 4 console.log('查询失败') 5 } else { 6 console.log(ret) 7 } 8 }) 9 //按条件查询 10 User.find({ 11 username: 'zs' 12 }, function (err, ret) { 13 if (err) { 14 console.log('查询失败') 15 } else { 16 console.log(ret) 17 } 18 }) 19 20 //只找匹配的第一个 没有条件会查询第一个插入的数据 21 User.findOne({ 22 username: 'zs' 23 }, function (err, ret) { 24 if (err) { 25 console.log('查询失败') 26 } else { 27 console.log(ret) 28 } 29 })
1 // 根据ID修改 2 User.findByIdAndUpdate('5a001b23d219eb00c8581184', { 3 password: '123' 4 }, function (err, ret) { 5 if (err) { 6 console.log('更新失败') 7 } else { 8 console.log('更新成功') 9 } 10 })
1 //有多少'zs' 删多少个 2 User.remove({ 3 username: 'zs' 4 }, function (err, ret) { 5 if (err) { 6 console.log('删除失败') 7 } else { 8 console.log('删除成功') 9 console.log(ret) 10 } 11 })