【问题标题】:Mongoose: find and select only the fields specified in a virtualMongoose:仅查找并选择虚拟中指定的字段
【发布时间】:2014-10-14 23:11:22
【问题描述】:

我在猫鼬中有一个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 放在那里,但在这种情况下我会重复代码。我可以避免吗?

【问题讨论】:

  • 现在没有可以尝试的 Node.js/Mongo shell,但我认为如果您只选择('profile'),它会起作用。代码重复是什么意思?如果你改变你的虚拟,你必须在两个地方改变这个?
  • 不,不幸的是,它只返回 _id 字段。是的,我不想在两个(或将来超过两个)地方更改相同的东西,以防万一。

标签: node.js mongoose


【解决方案1】:

根据mongooejs文档

只有非虚拟属性才能作为查询的一部分和字段选择。

你可以这样做

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

【讨论】:

    【解决方案2】:

    除了这个find 之外,您是否还在使用虚拟profile?您的虚拟实际上只是指定了一些字段,没有更多的动态,所以如果您只是想在查询中选择字段,我会坚持使用 (.select('username name role'))。如果你想让它可重用......只需将字符串作为模块中的值,你可以通过require 注入。然后你可以在任何你需要的地方改变它,像select(profileFields)一样使用它。

    【讨论】:

      猜你喜欢
      • 2014-08-12
      • 2015-06-10
      • 2012-11-07
      • 1970-01-01
      • 2018-08-31
      • 2022-07-07
      • 1970-01-01
      • 2016-02-05
      • 2020-05-16
      相关资源
      最近更新 更多