如何从结果中删除mongo特定字段(NodeJS,Mongoose)

时间:2015-11-19 09:05:09

标签: node.js mongodb mongoose

我想从查询结果中删除所有Mongo特定字段(例如'_id')。有没有一种简单的方法可以执行此操作,还是应该手动删除字段?如果是,那么哪些字段以及如何做?

我正在使用NodeJS和Mongoose

5 个答案:

答案 0 :(得分:3)

如果你想要隐藏_id属性,你可以使用带有前缀的文本参数 - 这将从结果中排除这个或那个字段,以获取你应该传递的特定字段:

Entity.find({ ... }, 'field1 field2', function(err, entity) {
    console.log(entity);  // { field1: '...', field2: '...' }
});

答案 1 :(得分:1)

您可以使用 projection 方法的可选第二个参数 find 字符串指定要从结果中排除的字段:

Model.find({}, "-a -b").then (res => {
    // objects in the res array will all have the 
    // 'a' and 'b' fields excluded. 
});

https://mongoosejs.com/docs/api.html#model_Model.find(见projection

答案 2 :(得分:0)

您可以使用select()方法从查询中删除该字段:

Model.find({}).select("-removed_field").then (resp => {
// your code        
});

您应该在字段名称前指定“-”,以删除该字段。 如果要删除多个字段,可以将其指定为数组:

Model.find({}).select(["-removed_field1", "-removed_field2" ... ]).then (resp => {
// your code        
});

使用这种方法,您还可以仅选择指定的字段,而不能使用“-”

Model.find({}).select(["field1", "field2" ... ]).then (resp => {
// your code        
});

答案 3 :(得分:0)

您可以使用猫鼬实例方法来显示所有文档中的特定字段

const userSchema = new mongoose.Schema({
email: {
type: String,
},

name: {
type: String,
maxlength: 128,
index: true,
trim: true,
},
});
userSchema.method({
   transform() {
   const transformed = {};
   const fields = ['name', 'email'];

      fields.forEach((field) => {
      transformed[field] = this[field];
      });
   return transformed;
   },
});
module.exports = mongoose.model('User', userSchema);

答案 4 :(得分:0)

OP提到“从结果中”,据我所知,这意味着从查询结果中删除,即查询结果将包含该字段,但将从查询结果中删除。

A SO answer here提到,要修改查询结果(不可变),我们必须使用toObject()方法将结果转换为Object(使其可变)。

要从查询结果中删除字段,

let immutableQueryResult = await Col.findById(idToBeSearched)
let mutableQueryResult = immutableQueryResult.toObject()
delete mutableQueryResult.fieldToBeRemoved
console.log(mutableQueryResult)

获取可变结果的另一种方法是使用结果的_doc属性:

let immutableQueryResult = await Col.findById(idToBeSearched)
let mutableQueryResult = immutableQueryResult._doc    // _doc property holds the mutable object
delete mutableQueryResult.fieldToBeRemoved
console.log(mutableQueryResult)