乐闻世界logo
搜索文章和话题

Mongoose 如何从集合中排除一个特定字段?

5 个月前提问
3 个月前修改
浏览次数59

6个答案

1
2
3
4
5
6

在 Mongoose 中,如果您想要从查询结果中排除特定的字段,您可以通过在查询的 select 方法中设置字段名前加上 - 符号来实现。这告诉 Mongoose 在查询结果中排除这些字段。

例如,假设我们有一个名为 User 的模型,它包含多个字段,例如 nameemailpassword。如果我们想要查询所有用户但不想在结果中包含 password 字段,我们可以这样编写查询:

javascript
User.find().select('-password').exec((err, users) => { if (err) throw err; // 处理不包含密码的用户数据 console.log(users); });

在上面的例子中,.find() 方法会检索集合中所有的文档,.select('-password') 会排除 password 字段。如果要排除多个字段,可以连续添加排除的字段,如 .select('-password -someOtherField')

另一种方式是在查询对象中直接使用字段选择符:

javascript
User.find({}, '-password', (err, users) => { if (err) throw err; // 处理不包含密码的用户数据 console.log(users); });

在这个例子中,第二个参数是一个字符串,指定了需要排除的字段(在字段名称前加上 -)。

还可以在查询对象中以对象的形式指定要排除的字段:

javascript
User.find({}, { password: 0 }, (err, users) => { if (err) throw err; // 处理不包含密码的用户数据 console.log(users); });

在这种情况下,我们通过 { password: 0 } 对象指定不要包括 password 字段,其中 0 表示排除该字段。

以上都是在查询时排除一个特定字段的方法,这样可以确保敏感信息不会被发送到客户端,也可以提升性能,因为少传输了数据。

2024年6月29日 12:07 回复

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:

shell
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.

2024年6月29日 12:07 回复

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:

shell
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.

2024年6月29日 12:07 回复

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.

2024年6月29日 12:07 回复

You could do this

shell
const products = await Product.find().select(['-image'])
2024年6月29日 12:07 回复

You can do it like this

shell
const products = await Product.find().select({ "image": 0 });
2024年6月29日 12:07 回复

你的答案