gpt4 book ai didi

node.js - Mongoose :仅查找并选择虚拟中指定的字段

转载 作者:搜寻专家 更新时间:2023-10-31 22:55:22 25 4
gpt4 key购买 nike

我在 mongoose 中有一个 UserSchema 模式:

var UserSchema = new Schema({
name: String,
username: String,
email: String,
role: {type: String, default: 'user'},
following: [{type: Schema.ObjectId, ref: 'User'}],
followers: [{type: Schema.ObjectId, ref: 'User'}],
hashedPassword: String,
provider: String,
salt: String,
facebook: {},
twitter: {},
github: {},
google: {}
});

我创建了一个虚拟的 profile,它只返回公开个人资料的信息:

UserSchema
.virtual('profile')
.get(function() {
return {
'username': this.username,
'name': this.name,
'role': this.role
};
});

我的问题是如何在发出 find 请求时仅获取此信息。这是我的代码:

UserSchema.statics = {
list: function (options, callback) {
var criteria = options.criteria || {};

this.find(criteria)
.select(/* What to put here? */)
.limit(options.perPage)
.skip(options.perPage * options.page)
.exec(callback);
}
};

当然,我可以简单地把 usernamenamerole 放在那里,但在那种情况下我会有代码重复。我可以避免这种情况吗?

最佳答案

根据mongooejs文档

Only non-virtual properties work as part of queries and for field selection.

你可以这样做

exports.show = function (req, res, next) {
var userId = req.params.id;

User.findById(userId, function (err, user) {
if (err) {
return next(err);
}
res.json(user.profile);
});
};

但不是这个

exports.devs = function (req, res, next) {
User.find({role: 'developer'}, 'developer_profile', function (err, users) {
if (err) {
return res.status(500).send(err);
}
res.status(200).json(users);
});
};

您可以在此处阅读更多信息 http://mongoosejs.com/docs/guide.html#virtuals

关于node.js - Mongoose :仅查找并选择虚拟中指定的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25424289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com