使用Mongoose查询MongoDB数据时如何仅提取结果中的url字段
解决方案
你可以通过两种方式实现仅提取url字段:
- 查询时直接指定返回字段(推荐)
Mongoose的find()方法支持传入第二个参数作为「投影配置」,明确指定需要返回的字段,不需要的字段可以主动排除:
router.get('/posts', async function (req, res, next) { // 第二个参数里,1表示返回该字段,0表示不返回该字段 // 默认会返回_id字段,如果不需要可以手动设置_id:0 let allPosts = await Post.find({}, { url: 1, _id: 0 }); console.log(allPosts) // 输出结果就是 [{url: 'xxx'}, {url: 'yyy'}]格式 })
如果只需要纯url组成的一维数组,可以搭配distinct方法直接获取:
const urls = await Post.distinct('url') // 输出结果直接是 ['xxx', 'yyy']
- 拿到全部查询结果后手动提取
如果已经通过Post.find()拿到了完整的文档数组,可以用数组map方法遍历提取:
let allPosts = await Post.find(); const urls = allPosts.map(post => post.url)
额外注意点
你当前POST路由的代码有字段名不匹配的问题:Schema里定义的时间字段是created_date,但你新建Post的时候写的是current_time: req.body.created_date,Schema里没有current_time字段,这条数据会被Mongoose自动忽略,导致存进去的created_date是空值,建议修改为:
const newPost = new Post({ url: req.body.url, description: req.body.description, created_date: req.body.created_date });
内容的提问来源于stack exchange,提问作者user11805652
相关产品推荐
相关产品推荐

