如何从文档中排除某些字段 [英] How to exclude some fields from the document
问题描述
我有以下简单的shema:
I have the following simple 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?
});
});
最后我想发送没有 _creator 字段的新创建的用户:
At the end I want to send the new created user without _creator field:
{
name: 'John',
age: 45
}
是否可以在没有额外查找请求的情况下向猫鼬发出请求?
Is it possible to make without extra find request to mongoose?
P.S:最好在
推荐答案
在架构级别处理此问题的另一种方法是覆盖模型的 toJSON.
Another way to handle this on the schema level is to override toJSON for the model.
UserSchema.methods.toJSON = function() {
var obj = this.toObject()
delete obj.passwordHash
return obj
}
我遇到了这个问题,正在寻找一种方法来从我提供给客户端的 json 中排除密码哈希,而 select: false
破坏了我的 verifyPassword 函数,因为它没有从数据库.
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.
这篇关于如何从文档中排除某些字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!