1

考虑我定义了一个Mongoose 模式

var Schema_MySchema = new mongoose.Schema({
Field1: String, Field2: String
});

我通过以下方式添加了虚拟属性和设置选项:

Schema_MySchema.virtual('USERNAME').get(function () {
    return this.Field1;
});

Schema_MySchema.set('toJSON', { virtuals: true });

使用 schema 对象从 MongoDB 中检索数据,如下所示:

var Mod_Obj = mongoose.model('SchemaName', Schema_MySchema);
var Model_Instance = new Mod_Obj();
Model_Instance.find({}, function (err, docs) {
   /* 
      Here I get a object docs with following structure:
      [{ _id: ObjectId("511XXXdff9c4c419000008"), 
          Field1: 'SOMEvalueFromMongoDB_1', 
          Field2: 'SOMEvalueFromMongoDB_2',
          USERNAME: 'SOMEvalueFromMongoDB_1'
      }]
  */
});

现在我想删除从 MongoDB 返回的实际属性,比如说我想从中Field1删除docs

我尝试了以下方法来删除:

1. delete docs.Field1;

2. var Json_Obj = docs.toJSON(); delete Json_Obj.Field1;

3. var Json_Obj = docs.toObject({ virtuals: true }); delete Json_Obj.Field1;

4. delete docs[0].Field1;

5. delete docs[0]['Field1'];

所有的方法都没有奏效。:-(

如果在简单的 JSON 上执行测试,它可以工作:

var a = { 'A' : 1, 'B': 2 };
delete a.A;
console.log(a); //prints only object with B attribute only. i.e. { B: 2 }

谁能告诉我这里有什么问题?

提前致谢...

4

4 回答 4

2

我相信您缺少索引和docs数组。

如果您的文档具有以下结构

[{ _id: ObjectId("511XXXdff9c4c419000008"), 
      Field1: 'SOMEvalueFromMongoDB_1', 
      Field2: 'SOMEvalueFromMongoDB_2',
      USERNAME: 'SOMEvalueFromMongoDB_1'
  }]

删除代码应该是

delete docs[index]['Field1']

IE。删除Field1第一个元素

delete docs[0]['Field1']

更新评论:

请参考这个答案

在这里你需要这样做

var k = docs[index].toObject();
delete k['Field1'];
于 2013-02-08T07:53:29.010 回答
1

删除字段后必须保存文档,尝试如下

var Mod_Obj = mongoose.model('SchemaName', Schema_MySchema);
var Model_Instance = new Mod_Obj();
Model_Instance.find({}, function (err, docs) {
   /* 
      Here I get a object docs with following structure:
      [{ _id: ObjectId("511XXXdff9c4c419000008"), 
          Field1: 'SOMEvalueFromMongoDB_1', 
          Field2: 'SOMEvalueFromMongoDB_2',
          USERNAME: 'SOMEvalueFromMongoDB_1'
      }]
  */
delete docs[0].Field1;
docs[0].save(function(err){
if(err){
console.log(err);
}else{
console.log("Field1 is deleted");
}
});
});
于 2013-02-08T08:38:14.667 回答
1

找到了一些解决方案。这是使用 Mongoose 的方法

schema.options.toObject.transform = function (doc, ret, options) {
  // remove the _id of every document before returning the result
  delete ret._id;
}

转到Document.toObject([options])然后滚动到主题Transform

于 2013-02-08T09:34:35.373 回答
0

您需要更新模型才能返回它。

toJSON: {
    virtuals: true,
    transform: function(doc, ret) {
         ret.id = ret._id;
         delete ret._id;
      }
}
于 2021-04-15T04:27:53.617 回答