前言
本文很大一部分是官方文档内容,如想了解更多,可直接查看文档。 NodeJs操作MongoDB官方文档
关于MongoDB的安装可以参见这篇文章: 一个前端小白的数据库之路:MongoDB和可视化工具的下载和安装
新建一个Node项目
首先,创建一个存放项目的文件夹 node_quickstart
mkdir node_quickstart
之后进入该文件
cd node_quickstart
再之后,初始化项目
npm init -y
然后,添加mongodb依赖包
npm install mongodb
然后新建一个mongo.js文件
NodeJS连接MongoDB
net start MongoDB 先启动数据库
// mongo.js文件
const { MongoClient } = require('mongodb');
const URL = 'mongodb://127.0.0.1:27017';
const mongo = async () => {
const client = new MongoClient(URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
retryWrites: true,
});
try {
await client.connect();
console.log('连接成功');
} catch (err) {
throw new Error(err);
} finally {
console.log('关闭-==---------------');
await client.close();
}
};
mongo();
启动脚本
node mongo.js
这。。。。。真的连接成功了吗??? 将结果打印下。
const result =await client.connect();
console.log('连接成功',result);
好像是成功了,只是看不大懂,返回的什么鬼。。。。
操作下数据库看看。
mongodb的增、查、改、删
自动更新
因为每次更改js文件内容,均需手动执行一次,很麻烦。有没有什么办法,让他自己更新呢?
有的,nodemon可以解决这个问题
- 安装依赖包
npm i nodemon
- 配置执行脚本
- 执行如下命令,这样就不用每次改动代码后,都要重启node服务啦~
npm run start
mongodb CURD操作
插入一条数据
const { MongoClient } = require('mongodb');
// Replace the uri string with your MongoDB deployment's connection string.
const uri = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
async function insertOne() {
try {
await client.connect();
const database = client.db('sample_mflix');
const movies = database.collection('movies');
// create a document to be inserted
const doc = { name: 'Red', town: 'kanto' };
const result = await movies.insertOne(doc);
console.log(
`${result.insertedCount} documents were inserted with the _id: ${result.insertedId}`
);
} finally {
await client.close();
}
}
insertOne().catch(console.dir);
插入多条数据
async function insertMany() {
try {
await client.connect();
const database = client.db('sample_mflix');
const movies = database.collection('movies');
// create an array of documents to insert
const docs = [
{ name: 'Red', town: 'Kanto' },
{ name: 'Blue', town: 'Kanto' },
{ name: 'Leon', town: 'Galar' },
];
// this option prevents additional documents from being inserted if one fails
const options = { ordered: true };
const result = await movies.insertMany(docs, options);
console.log(`${result.insertedCount} documents were inserted`);
} finally {
await client.close();
}
}
insertMany().catch(console.dir);
查找一条数据
async function findOne() {
try {
await client.connect();
const database = client.db('sample_mflix');
const movies = database.collection('movies');
// 查询参数
const query = { title: 'The Room' };
const options = {
// rating降序排列
sort: { rating: -1 },
// 重组返回的数据,包含1,不包含0
projection: { _id: 0, title: 1, imdb: 1 },
};
const movie = await movies.findOne(query, options);
// since this method returns the matched document, not a cursor, print it directly
console.log(movie);
} finally {
await client.close();
}
}
findOne().catch(console.dir);
查找多条数据
async function find() {
try {
await client.connect();
const database = client.db('sample_mflix');
const movies = database.collection('movies');
// query for movies that have a runtime less than 15 minutes
const query = { runtime: { $lt: 15 } };
const options = {
// sort returned documents in ascending order by title (A->Z)
sort: { title: 1 },
// Include only the `title` and `imdb` fields in each returned document
projection: { _id: 0, title: 1, imdb: 1 },
};
const cursor = movies.find(query, options);
// print a message if no documents were found
if ((await cursor.count()) === 0) {
console.log('No documents found!');
}
// replace console.dir with your callback to access individual elements
await cursor.forEach(console.dir);
} finally {
await client.close();
}
}
find().catch(console.dir);
更新一条数据
async function updateOne() {
try {
await client.connect();
const database = client.db('sample_mflix');
const movies = database.collection('movies');
// create a filter for a movie to update
const filter = { title: 'Blacksmith Scene' };
// this option instructs the method to create a document if no documents match the filter
const options = { upsert: true };
// create a document that sets the plot of the movie
const updateDoc = {
$set: {
plot: 'Blacksmith Scene is a silent film directed by William K.L. Dickson.',
},
};
const result = await movies.updateOne(filter, updateDoc, options);
console.log(
`${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`
);
} finally {
await client.close();
}
}
updateOne().catch(console.dir);
更新多条
async function updateMany() {
try {
await client.connect();
const database = client.db('sample_mflix');
const movies = database.collection('movies');
// create a filter to update all movies with a 'G' rating
const filter = { rated: 'G' };
// increment every document matching the filter with 2 more comments
const updateDoc = {
$inc: {
num_mflix_comments: 2,
},
};
const result = await movies.updateMany(filter, updateDoc);
console.log(result);
} finally {
await client.close();
}
}
updateMany().catch(console.dir);
替换一条数据
async function replaceOne() {
try {
await client.connect();
const database = client.db('sample_mflix');
const movies = database.collection('movies');
// create a query for a movie to update
const query = { title: 'Blacksmith Scene' };
const options = {
// create a document if no documents match the query
upsert: true,
};
// create a new document that will be used to replace the existing document
const replacement = {
title: 'Sandcastles in the Sand',
plot: 'Robin Sparkles mourns for a relationship with a mall rat at an idyllic beach.',
};
const result = await movies.replaceOne(query, replacement, options);
if (result.modifiedCount === 0 && result.upsertedCount === 0) {
console.log('No changes made to the collection.');
} else {
if (result.matchedCount === 1) {
console.log('Matched ' + result.matchedCount + ' documents.');
}
if (result.modifiedCount === 1) {
console.log('Updated one document.');
}
if (result.upsertedCount === 1) {
console.log(
'Inserted one new document with an _id of ' + result.upsertedId._id
);
}
}
} finally {
await client.close();
}
}
replaceOne().catch(console.dir);
删除一条数据
async function deleteOne() {
try {
await client.connect();
const database = client.db('sample_mflix');
const movies = database.collection('movies');
// Query for a movie that has a title of type string
const query = { title: { $type: 'string' } };
const result = await movies.deleteOne(query);
if (result.deletedCount === 1) {
console.dir('Successfully deleted one document.');
} else {
console.log('No documents matched the query. Deleted 0 documents.');
}
} finally {
await client.close();
}
}
deleteOne().catch(console.dir);
删除多条数据
async function deleteMany() {
try {
await client.connect();
const database = client.db('sample_mflix');
const movies = database.collection('movies');
// Query for all movies with the title "Santa Claus"
const query = { title: 'Santa Claus' };
const result = await movies.deleteMany(query);
console.log('Deleted ' + result.deletedCount + ' documents');
} finally {
await client.close();
}
}
deleteMany().catch(console.dir);
好了,到此你就可以愉快的操作数据库了。
真的可以愉快的操作了吗???
No!!!
后面的文章说说为啥不愉快