首页 > 解决方案 > MongoDB 投影参数在 findOne() 中不起作用

问题描述

我正在尝试在 findOne() 上使用投影参数从文档(统计信息)中提取单个字段,但它似乎只是返回了整个文档。我在 Node.js 中使用版本“mongodb”:“^3.4.1”

这是文档结构

{ _id: 5e563015fa9a1a0134cac3cb,
  username: 'user1',
  password: '1234',
  email: 'user@email.com',
  stats: 
   { totalViewed: 122,
     totalUnique: 4,
     tknow: 80,
     tdknow: 42,
     setCnt: 78 },
  progress: 
   [ { cardId: 1001, knowCnt: 3, dknowCnt: 4 },
     { cardId: 1016, knowCnt: 0, dknowCnt: 0 } ] }

这是代码:

 var findOneDoc = function() {
        db.collection("testusers").findOne(
          { username: "user1" },
          { stats: 1 }, //field to return
          function(err, result) {
            if (err) {
              console.log("Error: ", err);
            }
            console.log("Success: ", result);
          }
        );
      };
     findOneDoc();

我也试过:{$project: {stats: 1}},无济于事

谢谢

标签: node.jsmongodb

解决方案


根据文档,该.findOne()方法将选项作为第二个参数,建议用于projection定义字段:

db.collection("testusers").findOne(
    { username: "user1" },
    { projection: { stats: 1 } },
    function(err, result) { ... }
);

推荐阅读