[英]MongoDB find() and retrieve only a field of all documents
为什么打开此 API/测试页面会记录Users
集合中的整个文档而不仅仅是名称?
import { connectToDatabase } from "../../utils/mongodb"
export default async (req, res) => {
const { db } = await connectToDatabase();
try{
const userNames = await db.collection('Users').find({}, {name: 1, _id: 0}).toArray()
console.log('userNames '+JSON.stringify(userNames))
}catch(err){
console.log(err)
}
}
看来您正在使用 mongodb v3。 虽然您在上面使用的语法在 v2 中有效,但 v3 不再支持fields
参数。 您要么需要在选项 object 上传递投影属性,要么包括一个投影文档来指定或限制要返回的字段,例如.project({ name: 1, _id: 0 })
。
const userNames = await db.collection('Users')
.find({})
.project({ name: 1, _id: 0 })
.toArray()
// OR
const userNames = await db.collection('Users')
.find(
{},
{ projection: { name: 1, _id: 0 } }
)
.toArray()
MongoDB v3 中的更多更改: https://github.com/mongodb/node-mongodb-native/blob/master/CHANGES_3.0.0.md
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.