【问题标题】:Mongoose select: false not working on location nested object猫鼬选择:假不适用于位置嵌套对象
【发布时间】:2016-09-04 01:48:12
【问题描述】:

我希望我的架构的 location 字段默认隐藏。 我给它添加了select: false属性,但是选择文档时总是返回...

var userSchema = new mongoose.Schema({

cellphone: {
  type: String,
  required: true,
  unique: true,
},

location: {
  'type': {
    type: String,
    required: true,
    enum: ['Point', 'LineString', 'Polygon'],
    default: 'Point'
   },
   coordinates: [Number],
   select: false, <-- here
   },
});

userSchema.index({location: '2dsphere'});

调用时:

User.find({ }, function(err, result){ console.log(result[0]); });

输出是:

 {  
    cellphone: '+33656565656',
    location: { type: 'Point', coordinates: [Object] } <-- Shouldn't
 }

编辑:解释(感谢@alexmac)

SchemaType 选择选项必须应用于字段选项而不是类型。在您的示例中,您已经定义了一个复杂类型 Location 并向类型添加了选择选项。

【问题讨论】:

  • findOne呢,它会返回还是不返回?
  • 问题已解决。是的,findOne 也返回了它:)
  • 如果您分享您的解决方案会很好。 @MalteseFalcon

标签: node.js mongodb mongoose mongoose-schema


【解决方案1】:

您应该首先创建locationSchema,然后使用带有select: false 的架构类型:

var locationSchema = new mongoose.Schema({
    'type': {
        type: String,
        required: true,
        enum: ['Point', 'LineString', 'Polygon'],
        default: 'Point'
       },
       coordinates: [Number]
    }
});

var userSchema = new mongoose.Schema({
    location: {
      type: locationSchema,
      select: false
    }
});

【讨论】:

  • 我们已经接近了,坐标不再显示,但位置的其余部分是:"location": { "type": "Point" } 注意:我也添加了 select: false 到位置。
  • 好吧,我以为你只想隐藏coordinates字段,如果你想完全隐藏location,你应该为其定义架构并将其用作类型。
  • 你能不能把coordinates后面的括号去掉,把locationSchema后面的;替换成,。最后,您能否解释一下为什么 select 属性在嵌套对象中不能直接起作用?为什么我们必须声明外部模式?
  • SchemaType select 选项必须应用于字段选项而不是类型。在您的示例中,您定义了一个复杂类型 Location 并将 select 选项添加到类型。
猜你喜欢
  • 1970-01-01
  • 2015-09-15
  • 2014-07-26
  • 2013-10-07
  • 2020-09-06
  • 1970-01-01
  • 2014-07-28
  • 2016-11-09
  • 2016-04-11
相关资源
最近更新 更多