node.js 中使用 Mongodb
安装node的mongodb https://www.npmjs.com/package/mongodb
const MongoClient = require(‘mongodb‘).MongoClient;const assert = require(‘assert‘);// Connection URLconst url = ‘mongodb://localhost:27017‘;// Database Nameconst dbName = ‘admin‘;// Use connect method to connect to the serverMongoClient.connect(url, function(err, client) { // assert.equal(null, err); if (err) { console.log(err); return} console.log(‘数据库连接成功‘); const db = client.db(dbName); const collection = db.collection(‘admin‘); // 添加数据 // collection.insertMany([ // {‘name‘: ‘qqq‘, ‘age‘: ‘10‘}, // {‘name‘: ‘www‘, ‘age‘: ‘20‘}, // {‘name‘: ‘eee‘, ‘age‘: ‘30‘}, // ], function(err, result) { // if (err) { console.log(err); return} // // assert.equal(err, null); // // assert.equal(3, result.result.n); // // assert.equal(3, result.ops.length); // client.close(); // console.log(‘添加成功‘); // }); // 删除数据 // collection.deleteOne({ ‘name‘ : ‘qqq‘ }, function(err, result) { // if (err) { console.log(err); return} // // assert.equal(err, null); // // assert.equal(1, result.result.n); // // client.close(); // console.log(‘删除成功‘); // }); // 修改更新数据 collection.updateOne( { ‘name‘ : ‘www‘ }, { $set: { ‘name‘ : ‘111‘ } }, (err, result) => { if (err) { console.log(err); return} // assert.equal(err, null); // assert.equal(1, result.result.n); console.log(‘更新成功‘); client.close(); }); // 查看数据 collection.find({}).toArray(function(err, docs) { if (err) { console.log(err); return} // assert.equal(err, null); console.log(docs); client.close(); });});
相关推荐
lbyd0 2020-11-17
BigYellow 2020-11-16
sushuanglei 2020-11-12
我心似明月 2020-11-09
zhushenghan 2020-11-09
sunnnyduan 2020-10-16
不要皱眉 2020-10-14
xiaohai 2020-09-29
songxiugongwang 2020-09-22
萌亖 2020-09-17
LuckyLXG 2020-09-08
sdmzhu 2020-09-01
mkhhxxttxs 2020-09-16
xiaohai 2020-09-16
newcome 2020-09-09
jaylong 2020-08-19
大秦铁骑 2020-08-19
thatway 2020-08-19