猫鼬stringify删除空元素 [英] mongoose stringify removes empty elements
问题描述
我要从我的mongo数据库中获取一个带有空值的 mongoose 对象:
I am retreiving a mongoose object with an empty values from my mongo db :
{ _id: 53049728456d4416243bf65f,
userCreated: {},
status: { userCreated: {} },
user: 'patrice',
}
这很好,因为没有数据.
which is fine because there is no data.
但是当我使用 JSON.stringify(obj) stringify 时,我得到了:
But when I stringify with JSON.stringify(obj) this i get :
{ _id: 53049728456d4416243bf65f,
user: 'patrice'
}
userCreated 和 status 的键尚未进行字符串化,也不会出现在我的输出中...
the keys userCreated and status haven't been stringified and don't appear in my output...
有人知道这是从哪里来的,如何获得它吗?
Any idea where this comes from and how to get arrount it ?
我的模型是这样的:
new mongoose.Schema({
user: type: String, default: '',
status: {
name: { type: String, default: '' },
userCreated: {
time: { type: Date, default: Date.now }
}
},
userCreated: {
time: { type: Date, default: Date.now }
}
})
P.
推荐答案
JSON.stringify通常不会剥离空对象,因此这是猫鼬特有的.
JSON.stringify doesn't normally strip empty objects, so this is mongoose specific.
我建议尝试.toObject()或.toJSON()
I'd recommend trying .toObject() or .toJSON()
http://mongoosejs.com/docs/api.html#document_Document-toObject
该对象将在.stringify期间被调用,因此可能是切出空对象的原因. http://mongoosejs.com/docs/api.html#document_Document-toJSON
This one will get called during .stringify so it probably is what is cutting out the empty objects. http://mongoosejs.com/docs/api.html#document_Document-toJSON
因此,请首先尝试:
JSON.stringify(obj.toObject());
这篇关于猫鼬stringify删除空元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!