Mongoose中的select:false在嵌套对象location上不起作用。

9

我希望我的模式中的位置字段默认情况下应该是隐藏的。 我已经添加了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呢?它会返回它吗? - libik
问题已经解决。是的,findOne 也返回了它 :) - Scaraux
如果您能分享您的解决方案就太好了。@MalteseFalcon - Cozzbie
1个回答

4

首先,您应该创建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 } - Scaraux
好的,我以为你只想隐藏“coordinates”字段,如果你想完全隐藏“location”,你应该为它定义模式并将其用作类型。 - alexmac
你能否把coordinates后面的括号去掉,并将locationSchema后面的分号替换为逗号。 最后,你能否解释一下为什么选择属性不能直接在嵌套对象中使用?我们为什么要声明外部模式? - Scaraux
SchemaType的“select”选项必须应用于字段选项而不是类型。在您的示例中,您定义了一个复杂类型“Location”,并将“select”选项添加到了类型上。 - alexmac

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接