正常使用一个collection API来驱动是没有问题的,但是使用第二次API操作和mongo自己生成的_id,会报错:
MongoError: E11000 duplicate key error collection: runoob.orders index: id dup key: { : 1 }
查了帖子https://blog.csdn.net/Xiongtm/article/details/77650448?locationNum=10&fps=1
但是没用他的方法解决问题,因为我的数据已经带了_id,但是受到了启发,就是时间戳。
方法是加一个setTimout(),即可实现运用第2,3,4次API,更多的还没尝试。
用nodejs驱动mongodb的好像不多,继续趟坑。
贴一下代码:
var MongoClient = require(‘mongodb’).MongoClient;
var url = “mongodb://127.0.0.1:27017/”;
var orders={_id:1,product_id:154,status:1};
var products=[{_id:154,name:‘笔记本电脑’},{_id:155,name:‘耳机’},{_id:156,name:‘台式电脑’}];
MongoClient.connect(url, function (err, db) {
if (err) throw err;
console.log(‘数据库已创建’);
var dbo = db.db(“test”);
dbo.createCollection(‘orders’, function (err, res) {
if (err) throw err;
console.log(“创建集合!”);
setTimeout(()=>{
dbo.collection(‘orders’).insertOne(orders,function(err,res){
if(err)throw err;
console.log(‘文档插入成功’);
db.close();},100);
});});});
MongoClient.connect(url, function (err, db) {
if (err) throw err;
console.log(‘数据库已创建’);
var dbo = db.db(“test”);
dbo.createCollection(‘products’, function (err, res) {
if (err) throw err;
console.log(“创建集合!”);
setTimeout(()=>{
dbo.collection(‘products’).insertMany(products,function(err,res){
if(err)throw err;
console.log(‘文档插入成功’);
db.close();},100); });});});