How to exclude one particular field from a collect

2019-01-22 05:29发布

问题:

I have a NodeJS application with Mongoose ODM(Mongoose 3.3.1). I want to retrieve all fields except 1 from my collection.For Example: I have a collection Product Which have 6 fields,I want to select all except a field "Image" . I used "exclude" method, but got error.. This was my code.

    var Query = models.Product.find();
    Query.exclude('title Image');

    if (req.params.id) {
        Query.where('_id', req.params.id);
    }


    Query.exec(function (err, product) {
        if (!err) {
            return res.send({ 'statusCode': 200, 'statusText': 'OK', 'data': product });
        } else {
            return res.send(500);
        }
    });

But this returns error

Express
500 TypeError: Object #<Query> has no method 'exclude'.........

Also I tried, var Query = models.Product.find().exclude('title','Image'); and var Query = models.Product.find({}).exclude('title','Image'); But getting the same error. How to exclude one/(two) particular fields from a collection in Mongoose.

回答1:

Use query.select for field selection in the current (3.x) Mongoose builds.

Prefix a field name you want to exclude with a -; so in your case:

Query.select('-Image');

Quick aside: in JavaScript, variables starting with a capital letter should be reserved for constructor functions. So consider renaming Query as query in your code.



回答2:

I don't know where you read about that .exclude function, because I can't find it in any documentation.

But you can exclude fields by using the second parameter of the find method.

Here is an example from the official documentation:

db.inventory.find( { type: 'food' }, { type:0 } )

This operation returns all documents where the value of the type field is food, but does not include the type field in the output.



回答3:

Model.findOne({ _id: Your Id}, { password: 0, name: 0 }, function(err, user){
  // put your code
});

this code worked in my project. Thanks!! have a nice day.