我想将我的 MongoDB 查询应用于 Javascript(select 特定列)

I want to apply my MongoDB query to Javascript(select specific column)

嗨,我正在使用我的 MongoDB 和 NestJS。

我正在通过下面的查询进行测试。这正是我所期望的

我只想得到'_id'。所以我也测试了我的代码。

// // This is what I use(including comments)
// const { MongoClient, ObjectID } = require('mongodb');

// const url = 'mongodb+srv://alex:~ something';
// console.log(url);
// const client = new MongoClient(url);

// // Database Name
// const dbName = 'testDB';

export async function getCreaterPubGameId(authorID: string) {
  await client.connect();
  console.log('Connected successfully to server : update, find or insertData');
  const db = client.db(dbName);
  const collection = db.collection('games');

  return new Promise(function (resolve, reject) {
    collection.find({ authorID }, { type: '_id' }).toArray((err, doc) => {
      if (err) {
        reject(err);
      } else {
        console.log('getAlldata : ', doc);
        resolve(doc);
      }
    });
  });
}

使用这个函数后,我得到了MongoDB的所有数据。

如您所见,我使用了相同的语法。但是我得到了所有的数据。 有没有人有什么好主意??

使用MongoDbNode.js客户端需要使用投影

export async function getCreaterPubGameId(authorID: string) {
  await client.connect();
  console.log('Connected successfully to server : update, find or insertData');
  const db = client.db(dbName);
  const collection = db.collection('games');

  return new Promise(function (resolve, reject) {
    collection.find({ authorID }, { "type": 1}).toArray((err, doc) => {
      if (err) {
        reject(err);
      } else {
        console.log('getAlldata : ', doc);
        resolve(doc);
      }
    });
  });
}

当您将 1 传递给任何字段时,它将被添加到 prjection 字段中,并且只会显示那些架构字段。默认情况下 _id 将被包含,如果你不想包含它传递 _id: 0.

export async function getCreaterPubGameId(authorID: string) {
  await client.connect();
  console.log('Connected successfully to server : update, find or insertData');
  const db = client.db(dbName);
  const collection = db.collection('games');

// I have to use 'projection'
  return new Promise(function (resolve, reject) {
    collection.find({ authorID }, { projection: { _id: true }).toArray((err, doc) => {
      if (err) {
        reject(err);
      } else {
        console.log('getAlldata : ', doc);
        resolve(doc);
      }
    });
  });
}

Link : https://mongodb.github.io/node-mongodb-native/3.2/api/Collection.html#find