如何解决如何在Node.js的中间件中使用MongoDB查询保存数据
我想使用mongodb查询并使用node.js中的中间件来保存数据。请提供一些带有示例的代码?
解决方法
尝试一下。它适用于插入和更新(upsert)。
// app.js
const express = require('express');
const bodyParser = require('body-parser');
const MongoClient = require('mongodb').MongoClient;
const mongodb_url = process.env.MONGO_URL || "mongodb://localhost:27017";
const mongodb_dbname = 'test_db';
const port = process.env.PORT || 3006;
const app = express();
app.use(express.json())
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json({ extended: true}));
app.post('/api/post/:identifier',(req,res) => {
const identifier = req.params.identifier;
const content = req.body.payload;
MongoClient.connect(`${mongodb_url}`,{ useNewUrlParser: true },(err,client) => {
if (!err) {
let db = client.db(mongodb_dbname);
db.collection('posts')
.updateOne(
{ identifier: identifier },{ $set: { content: content } },{ upsert: true }
)
.then((output) => {
res.status(202).send({ message: "Sent"});
})
.catch((error) => {
res.status(500).send({
error_code: 500,error_message: `Error while updating data - ${error}`
});
});
client.close();
} else {
res.status(500).send({
error_code: 500,error_message: 'Error while connecting to database'
});
}
});
});
app.listen(port,() => {
console.log(`API bootstrapped on port ${port}...`);
});
使用以下package.json
文件:
{
"name": "mongo-upsert","version": "1.0.0","description": "","main": "index.js","scripts": {
"start": "node app.js","test": "echo \"Error: no test specified\" && exit 1"
},"keywords": [],"author": "","license": "ISC","dependencies": {
"express": "^4.17.1","mongodb": "^3.6.0"
}
}
当以localhost:3006/api/post/my-post
的形式调用且包含以下内容的请求正文时
{
"payload": "Hello world"
}
此代码将向上插入MongoDB文档,例如:
{
"_id" : ObjectId("5f3d272cbd52c9c109ea9baa"),"identifier" : "my-post","content" : "Hello world"
}
以上代码起作用的前提条件:
- 要正常安装
mongodb
- 拥有一个名为
test_db
的数据库 - 拥有一个名为
posts
的集合
在此示例中,我们将添加由content
标识的帖子identifier
,为简单起见,我将其添加为POST
定义中的路径参数。 / p>
使用npm install
安装依赖项。
使用npm start
运行应用。
祝你好运。
,我没有足够的代表发表评论,所以这是一个答案。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。