簡體   English   中英

MongoDB find() 並僅檢索所有文檔的一個字段

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM