主题
实现文章增删改查
文章管理是内容类应用的核心功能,合理设计并实现文章的增删改查操作至关重要。
文章数据模型设计
常见字段包括:
json
{
"title": "string",
"content": "string",
"authorId": "ObjectId",
"tags": ["string"],
"createdAt": "date",
"updatedAt": "date"
}
增加文章
js
const article = {
title: 'MongoDB 入门教程',
content: '这是文章内容...',
authorId: someUserId,
tags: ['mongodb', '数据库', '教程'],
createdAt: new Date(),
updatedAt: new Date()
};
const result = await db.collection('articles').insertOne(article);
console.log('Inserted article ID:', result.insertedId);
查询文章
- 查询所有文章:
js
const articles = await db.collection('articles').find().toArray();
- 根据 ID 查询单篇文章:
js
const article = await db.collection('articles').findOne({ _id: ObjectId(articleId) });
更新文章
js
await db.collection('articles').updateOne(
{ _id: ObjectId(articleId) },
{ $set: { title: '新标题', updatedAt: new Date() } }
);
删除文章
js
await db.collection('articles').deleteOne({ _id: ObjectId(articleId) });
说明
- 以上操作示例均基于 Node.js 原生驱动,需引入
mongodb
包并连接数据库。 - 适当添加索引(如作者 ID、标签)可提高查询效率。
- 结合业务需求,可扩展评论、点赞等功能。
通过以上示例,开发者可快速实现文章的增删改查,支持内容管理应用的基本需求。