NodeJS下的Mongodb操作

时间:2023-03-10 06:36:16
NodeJS下的Mongodb操作

今天用Node写一个小程序中需要用到数据库操作,试用了一下,发现官方的驱动已经非常好用了,也支持async。

一个简单的实例如下:

const
MongoClient
=
require('mongodb').MongoClient;

const
url
=
'mongodb://127.0.0.1:27017';
let
client
=
await
MongoClient.connect(url, { useNewUrlParser: true });

let
db
=
client.db('test');
let
collection
=
db.collection("user");

var
obj
= { name: 'jim', age: 21 };
await
collection.insertOne(obj);

gridfs操作也比较简单:

const
mongodb
=
require('mongodb');
const
fs
=
require('fs');

const
url
=
'mongodb://127.0.0.1:27017';
let
client
=
await
mongodb.MongoClient.connect(url, { useNewUrlParser: true });

let
db
=
client.db('test');
var
bucket
=
new
mongodb.GridFSBucket(db, { chunkSizeBytes: 1024
*
1024, bucketName: 'image' });
await
fs.createReadStream('./3.jpg').pipe(bucket.openUploadStream('3.jpg'));

同时,觉得现在VS Code写Node程序已经非常给力了,不仅调试功能非常好用,智能提示也非常棒,以后Node程序就用它了。

NodeJS下的Mongodb操作