如何从猫鼬的集合中排除一个特定字段? [英] How to exclude one particular field from a collection in Mongoose?

查看:82
本文介绍了如何从猫鼬的集合中排除一个特定字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有Mongoose ODM( Mongoose 3.3.1 )的NodeJS应用程序.我想从集合中检索除1外的所有字段.例如:我有一个集合Product,其中有6个场,我想选择除"Image"外的所有场.我使用了"排除"方法,但出现了错误. 这是我的代码.

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);
        }
    });

但这会返回错误

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

我也尝试过var Query = models.Product.find().exclude('title','Image');var Query = models.Product.find({}).exclude('title','Image');,但是得到了相同的错误.如何从猫鼬的集合中排除一个/(两个)特定字段.

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.

推荐答案

使用 query.select 用于当前(3.x)猫鼬版本中的字段选择.

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');

简单点:在JavaScript中,应保留以大写字母开头的变量以供构造函数使用.因此,请考虑在代码中将Query重命名为query.

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.

这篇关于如何从猫鼬的集合中排除一个特定字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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