1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| // db.js const MongoClient = require('mongodb').MongoClient; const dburl = "mongodb://localhost:27017"; const dbCollectionName = 'yyy' const dbName = "xxx" // 连接数据库 let dbo = null async function dbconnect(){ const db = await MongoClient.connect(dburl, { useNewUrlParser: true, useUnifiedTopology: true }) dbo = db.db(dbName); } // 查找数据 async function find(cod){ const dbData = await dbo .collection(dbCollectionName) .find({ // 查询条件 ...cod }).toArray(); console.log(dbData) } // 获取最新索引下标 async getNextSequence() { const res = await dbo.collection(dbCollectionName).findOneAndUpdate( { increase: 1, }, { $inc: { id: 1, }, $set: { des: "This line record total num", }, }, { upsert: true, new: true, // "returnOriginal": false } ); return res.value ? res.value.id : 0; } // 插入 async function inset(){ dbo.collection(dbCollectionName).insertOne({ id: getNextSequence() + 1, // 其他需要插入的数据 }); } // 更新 async function update(){ const recordItem = await find({...}) await dbo.collection(dbCollectionName).updateOne({ _id: recordItem._id }, { $set: { // 需更新数据 } }); }
|