const MongoClient = require('mongodb').MongoClient
const client = new MongoClient('mongodb://localhost:27017/', {useNewUrlParser: true})
client.connect(err=>{
if (err) throw err
const db = client.db('my_data')
const collection = db.collection('users')
/* 创建unique索引防止重复 */
// collection.createIndex({'name': 1}, {unique: true})
/* 增 */
collection.insertOne({
name: 'yokiijay',
age: 23
})
collection.insertMany([
{name: 'xiaoming', age: 18},
{name: 'laowang', age: 30}
], (err, data)=>{
if (err) throw err
console.log( data )
})
/* 删 */
collection.deleteOne({
name: 'laowang'
},(err,data)=>{
if (err) throw err
})
/* 改 */
collection.updateOne({name: 'xiaoming'}, {$set:{age: 22}},(err,data)=>{
if (err) throw err
console.log( data )
})
/* 查 */
collection.findOne({
name: 'yokiijay'
}).then(data=>{
console.log( data )
})
client.close()
})
网友评论