1.插入单条 -- insertOne
var MongoClient = require('mongodb').MongoClient; var url = require('./config/keys').mongoURI; /** * 插入单条 * insertOne */ MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, function(err, db) { if(err) throw err; var dbo = db.db('koa'); // koa 库名 var myobj = { name: '测试人员', type: 1, like: ['唱', '跳', '搞代码']}; dbo.collection('users').insertOne(myobj, function(err, res) { // users 表名 if(err) throw err; console.log('人员信息插入成功', res); db.close(); }) });
2.插入多条 -- insertMany
var MongoClient = require('mongodb').MongoClient; var url = require('./config/keys').mongoURI; /** * 插入多条 * insertMany */ MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, function(err, db) { if(err) throw err; var dbo = db.db('koa'); // koa 库名 var myobj = [ { name: '张三', type: 1, like: ['唱', '跳', '搞代码']}, { name: '李四', type: 1, like: ['唱', '跳', '搞代码']}, { name: '王五', type: 1, like: ['唱', '跳', '搞代码']} ]; dbo.collection('users').insertMany(myobj, function(err, res) { // users 表名 if(err) throw err; console.log('人员信息插入成功', res.insertedCount); db.close(); }) });
.