使用Node.js REST API实现MongoDB中votes数组追加布尔值true的方法
实现方案
核心采用MongoDB自带的$push原子操作符实现数组追加,无需先查询全量文档再修改,可避免并发调用时的数组元素覆盖问题,操作可靠性更高。
实现前请确认API调用时可获取到待更新文档的_id参数,一般通过接口路径参数或请求体传入即可。
1. 基于Mongoose的实现(Node.js生态最常用方案)
步骤1:定义对应Schema与Model
const mongoose = require('mongoose'); // 和你现有数据库结构匹配的Schema定义 const itemSchema = new mongoose.Schema({ createdAt: Number, description: String, email: String, phone: String, tags: [String], votes: [Boolean] }); const Item = mongoose.model('Item', itemSchema);
步骤2:编写API接口逻辑(以Express框架为例)
app.post('/api/items/:id/vote', async (req, res) => { try { const targetDocId = req.params.id; // 核心更新逻辑:$push往votes数组末尾追加true const updatedDoc = await Item.findByIdAndUpdate( targetDocId, { $push: { votes: true } }, { new: true } // 可选配置:返回更新后的文档,不需要可删除 ); if (!updatedDoc) { return res.status(404).json({ message: '待更新文档不存在' }); } res.status(200).json({ data: updatedDoc }); } catch (err) { res.status(500).json({ message: '更新失败', error: err.message }); } });
2. 基于原生MongoDB Node.js驱动的实现
如果不使用Mongoose,直接用官方原生驱动的实现如下:
const { MongoClient, ObjectId } = require('mongodb'); const client = new MongoClient('你的MongoDB连接字符串'); app.post('/api/items/:id/vote', async (req, res) => { try { await client.connect(); const db = client.db('你的数据库名称'); const itemsCollection = db.collection('你的集合名称'); const targetDocId = req.params.id; const updateResult = await itemsCollection.updateOne( // 注意:如果你的_id是默认的ObjectId类型,需要把字符串参数转成ObjectId { _id: new ObjectId(targetDocId) }, { $push: { votes: true } } ); if (updateResult.matchedCount === 0) { return res.status(404).json({ message: '待更新文档不存在' }); } res.status(200).json({ message: '投票成功' }); } catch (err) { res.status(500).json({ message: '更新失败', error: err.message }); } finally { await client.close(); } });
内容的提问来源于stack exchange,提问作者Heman Kadariya
相关产品推荐
相关产品推荐

