Javascript 如何从文档中排除某些字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11160955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to exclude some fields from the document
提问by Erik
I have the following simple shema:
我有以下简单的shema:
var userSchema = new Schema({
name : String,
age: Number,
_creator: Schema.ObjectId
});
var User = mongoose.model('User',userSchema);
What I want to do is create the new document and return to client, but I want to exclude the 'creator' field from one:
我想要做的是创建新文档并返回给客户端,但我想从其中排除“创建者”字段:
app.post('/example.json', function (req, res) {
var user = new User({name: 'John', age: 45, _creator: 'some ObjectId'});
user.save(function (err) {
if (err) throw err;
res.json(200, {user: user}); // how to exclude the _creator field?
});
});
At the end I want to send the new created user without _creator field:
最后,我想发送没有 _creator 字段的新创建的用户:
{
name: 'John',
age: 45
}
Is it possible to make without extra find request to mongoose?
是否可以在没有额外查找请求的情况下向猫鼬提出请求?
P.S:It's preferable to make it by
PS:最好通过
回答by Charles
Another way to handle this on the schema level is to override toJSON for the model.
在架构级别处理此问题的另一种方法是覆盖模型的 toJSON。
UserSchema.methods.toJSON = function() {
var obj = this.toObject()
delete obj.passwordHash
return obj
}
I came across this question looking for a way to exclude password hash from the json i served to the client, and select: false
broke my verifyPassword function because it didn't retrieve the value from the database at all.
我遇到了这个问题,正在寻找一种方法来从我提供给客户端的 json 中排除密码哈希,并select: false
破坏了我的 verifyPassword 函数,因为它根本没有从数据库中检索值。
回答by Xerri
The documented way is
记录的方式是
UserSchema.set('toJSON', {
transform: function(doc, ret, options) {
delete ret.password;
return ret;
}
});
UPDATE - You might want to use a white list:
更新 - 您可能想要使用白名单:
UserSchema.set('toJSON', {
transform: function(doc, ret, options) {
var retJson = {
email: ret.email,
registered: ret.registered,
modified: ret.modified
};
return retJson;
}
});
回答by Rex
Come across your question when I was trying to find a similar answer with pymongo. It turns out that in mongo shell, with the find() function call, you can pass a second parameter which specifies how the result document looks like. When you pass a dictionary with attribute's value being 0, you are excluding this field in all the document that come out of this query.
当我试图用 pymongo 找到类似的答案时,遇到了你的问题。事实证明,在 mongo shell 中,通过 find() 函数调用,您可以传递第二个参数,该参数指定结果文档的外观。当您传递属性值为 0 的字典时,您将在此查询中出现的所有文档中排除此字段。
In your case, for example, the query will be like:
例如,在您的情况下,查询将类似于:
db.user.find({an_attr: a_value}, {_creator: 0});
It will exclude _creator parameter for you.
它将为您排除 _creator 参数。
In pymongo, the find() function is pretty much the same. Not sure how it translate to mongoose though. I think it's a better solution compare to manually delete the fields afterwards.
在 pymongo 中, find() 函数几乎相同。不知道它是如何转化为猫鼬的。我认为与之后手动删除字段相比,这是一个更好的解决方案。
Hope it helps.
希望能帮助到你。
回答by JohnnyHK
You can call toObject()
on the document to convert it to a plain JS object that you can freely modify:
您可以调用toObject()
文档将其转换为可以自由修改的普通 JS 对象:
user = user.toObject();
delete user._creator;
res.json(200, {user: user});
回答by fernandopasik
I would use the lodash utilities .pick()or .omit()
var _ = require('lodash');
app.post('/example.json', function (req, res) {
var user = new User({name: 'John', age: 45, _creator: 'some ObjectId'});
user.save(function (err) {
if (err) throw err;
// Only get name and age properties
var userFiltered = _.pick(user.toObject(), ['name', 'age']);
res.json(200, {user: user});
});
});
The other example would be:
另一个例子是:
var _ = require('lodash');
app.post('/example.json', function (req, res) {
var user = new User({name: 'John', age: 45, _creator: 'some ObjectId'});
user.save(function (err) {
if (err) throw err;
// Remove _creator property
var userFiltered = _.omit(user.toObject(), ['_creator']);
res.json(200, {user: user});
});
});
回答by Leo Ribeiro
By following the MongoDB documentation, you can exclude fields by passing a second parameter to your query like:
通过遵循 MongoDB 文档,您可以通过将第二个参数传递给您的查询来排除字段,例如:
User.find({_id: req.user.id}, {password: 0})
.then(users => {
res.status(STATUS_OK).json(users);
})
.catch(error => res.status(STATUS_NOT_FOUND).json({error: error}));
In this case, password will be excluded from the query.
在这种情况下,密码将从查询中排除。
字体:https: //docs.mongodb.com/v2.8/tutorial/project-fields-from-query-results/#return-all-but-the-excluded-field
回答by fino
I am using Mongoosemask and am very happy with it.
我正在使用 Mongoosemask 并且对它非常满意。
It does support hiding and exposing properties with other names based on your need
它确实支持根据您的需要使用其他名称隐藏和公开属性
https://github.com/mccormicka/mongoosemask
https://github.com/mccormicka/mongoosemask
var maskedModel = mongomask.mask(model, ['name', 'age']); //And you are done.
var maskedModel = mongomask.mask(model, ['name', 'age']); //你就完成了。