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

Posted

技术标签:

【中文标题】我想将我的 MongoDB 查询应用于 Javascript(选择特定列)【英文标题】:I want to apply my MongoDB query to Javascript(select specific column) 【发布时间】:2022-01-20 02:54:58 【问题描述】:

您好,我正在使用我的 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 中获取了所有数据。

如您所见,我使用了相同的语法。但我得到了所有的数据。 有谁有好的想法吗?

【问题讨论】:

【参考方案1】:

使用 MongoDb Node.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

【讨论】:

【参考方案2】:
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);
      
    );
  );

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

【讨论】:

以上是关于我想将我的 MongoDB 查询应用于 Javascript(选择特定列)的主要内容,如果未能解决你的问题,请参考以下文章

将 mongoDB 实例数据库链接到流星本地

我想将我的应用程序目标sdk版本29降级到28,google play控制台可以允许吗?

我想使用 Laravel 7 将我的查询输出传递到 jQuery 图表 js

我想将我的媒体播放器从一个 surafceview 更改为另一个 surafceview 如何在 android 中做到这一点?

我应该将我的 Nuxt 应用程序直接部署到 Google App Engine 还是应该在我的代码存在于存储库中的地方使用 Gitlab CI/CD?

我想将我的 dexie 值更改为空字符串