1.使用直连方法,连接MongoDB数据,在一个s文件中完成图书信息的增删改查图书结构如下。 Var book={ name:Web前端 price:38 publisher:清华大学出版社}
时间: 2024-05-01 20:24:09 浏览: 14
首先需要安装mongodb模块:
```
npm install mongodb --save
```
然后在s文件中编写以下代码:
```javascript
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'library';
const collectionName = 'books';
// 连接MongoDB数据库
MongoClient.connect(url, function(err, client) {
if (err) throw err;
console.log('MongoDB Connected!');
const db = client.db(dbName);
// 插入一本新书
db.collection(collectionName).insertOne({
name: 'Web前端',
price: 38,
publisher: '清华大学出版社'
}, function(err, result) {
if (err) throw err;
console.log('Book inserted!');
console.log(result);
});
// 更新一本书的价格
db.collection(collectionName).updateOne({ name: 'Web前端' }, { $set: { price: 42 } }, function(err, result) {
if (err) throw err;
console.log('Book updated!');
console.log(result);
});
// 查找一本书
db.collection(collectionName).findOne({ name: 'Web前端' }, function(err, result) {
if (err) throw err;
console.log('Book found!');
console.log(result);
});
// 删除一本书
db.collection(collectionName).deleteOne({ name: 'Web前端' }, function(err, result) {
if (err) throw err;
console.log('Book deleted!');
console.log(result);
});
// 关闭连接
client.close();
});
```
其中,`url`是MongoDB的连接地址,`dbName`是数据库名称,`collectionName`是集合名称。我们通过`MongoClient.connect()`方法连接MongoDB数据库,并获取到`db`对象,然后就可以进行增删改查操作了。
注意,在每个操作完成后,需要调用`client.close()`方法关闭连接。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)