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