带有投影以排除_id的Node.js MongoDB Find仍返回它 [英] Node.js MongoDB Find with projection to exclude _id still returns it

查看:50
本文介绍了带有投影以排除_id的Node.js MongoDB Find仍返回它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试按照示例此处进行过滤,方法是使用排除_id的投影. _id仍然返回:

Trying to follow the examples here to filter by using a projection to exclude _id. The _id still returns:

代码

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

MongoClient.connect(url, function (err, db) {
    if (err) throw err;
    var dbase = db.db("db1"); //here    

    dbase.collection("customers").find(
        {},
        {
            _id: 0

        }
        ).toArray(function(err, result) {
        if (err) throw err;
        console.log(result);
        db.close();
    });

});

结果仍然返回如下:

[{_id:5a2bb2d6ee48575cb54c4365, 名称:约翰", 地址:"Highway 71"},{_id:5a2bb2d6ee48575cb54c436d, 名称:苏珊", 地址:单向98"),.... {_id:5a2bb2d6ee48575cb54c4371, 名称:"Chuck", 地址:"Main Road 989"},{_id:5a2bb2d6ee48575cb54c4372, 名称:中提琴", 地址:"Sideway 1633'}]

[ { _id: 5a2bb2d6ee48575cb54c4365, name: 'John', address: 'Highway 71' }, { _id: 5a2bb2d6ee48575cb54c436d, name: 'Susan', address: 'One way 98' }, .... { _id: 5a2bb2d6ee48575cb54c4371, name: 'Chuck', address: 'Main Road 989' }, { _id: 5a2bb2d6ee48575cb54c4372, name: 'Viola', address: 'Sideway 1633' } ]

从理论上讲,_id不应成为返回值的一部分.怎么了?

Theoretically _id should not be part of what is returned. What is wrong here?

推荐答案

要限制字段,您必须使用fields选项(不知道新更新):

To limit the fields you have to use fields option( dont know about new updates):

dbase.collection("customers").find(
        {},
        {fields:{_id: 0}}
        ).toArray(function(err, result) {
        if (err) throw err;
        console.log(result);
        db.close();
    });

更新:

对于版本3以上,您必须改用projection选项:

For version > 3 you have to use projection option instead:

dbase.collection("customers").find(
        {},
        {projection:{_id: 0}}
        ).toArray(function(err, result) {
        if (err) throw err;
        console.log(result);
        db.close();
    });

这篇关于带有投影以排除_id的Node.js MongoDB Find仍返回它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆