Suppress _id on MongoDB

时间:2018-02-01 18:15:41

标签: node.js mongodb

I am learning MongoDB with this tutorial https://www.w3schools.com/nodejs/nodejs_mongodb_find.asp and running the tests on the v3.4.11.

I am having issues with the following exercise which is supposed to show all the documents in the collection but without the _id field:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("mydb");
  dbo.collection("customers").find({}, { _id: 0 }).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
  });
});

But what I get is the full list with all the fields:

[ { _id: 5a734e6e77a6510d2193b4df,
    name: 'Company Inc',
    address: 'Highway 37' },
  { _id: 5a734e8e7c3e9a0d35a604c3,
    name: 'John',
    address: 'Highway 71' },
  { _id: 5a734e8e7c3e9a0d35a604c4,
    name: 'Peter',
    address: 'Lowstreet 4' },
  { _id: 5a734e8e7c3e9a0d35a604c5,
    name: 'Amy',
    address: 'Apple st 652' },
  { _id: 5a734e8e7c3e9a0d35a604c6,
    name: 'Hannah',
    address: 'Mountain 21' },
  { _id: 5a734e8e7c3e9a0d35a604c7,
    name: 'Michael',
    address: 'Valley 345' },
  { _id: 5a734e8e7c3e9a0d35a604c8,
    name: 'Sandy',
    address: 'Ocean blvd 2' },
  { _id: 5a734e8e7c3e9a0d35a604c9,
    name: 'Betty',
    address: 'Green Grass 1' },
  { _id: 5a734e8e7c3e9a0d35a604ca,
    name: 'Richard',
    address: 'Sky st 331' },
  { _id: 5a734e8e7c3e9a0d35a604cb,
    name: 'Susan',
    address: 'One way 98' },
  { _id: 5a734e8e7c3e9a0d35a604cc,
    name: 'Vicky',
    address: 'Yellow Garden 2' },
  { _id: 5a734e8e7c3e9a0d35a604cd,
    name: 'Ben',
    address: 'Park Lane 38' },
  { _id: 5a734e8e7c3e9a0d35a604ce,
    name: 'William',
    address: 'Central st 954' },
  { _id: 5a734e8e7c3e9a0d35a604cf,
    name: 'Chuck',
    address: 'Main Road 989' },
  { _id: 5a734e8e7c3e9a0d35a604d0,
    name: 'Viola',
    address: 'Sideway 1633' } ]

Does anyone know what am I doing wrong?

1 个答案:

答案 0 :(得分:1)

You have to put projections in a nested projection property in the options parameter of find.

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("mydb");
  dbo.collection("customers")
  .find({}, { projection: { _id: 0 } })
  .toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
  });
});

The node mongodb driver is slightly different than just using mongodb shell syntax, so make sure you're looking up the node mongodb driver docs, specific to your version. https://mongodb.github.io/node-mongodb-native/