Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

javascript - How to exclude one particular field from a collection in Mongoose?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...