gpt4 book ai didi

node.js - mongoose stringify 删除空元素

转载 作者:太空宇宙 更新时间:2023-11-04 03:10:26 25 4
gpt4 key购买 nike

我正在从我的 mongo 数据库中检索一个带有空值的 mongoose 对象:

{ _id: 53049728456d4416243bf65f,
userCreated: {},
status: { userCreated: {} },
user: 'patrice',
}

这很好,因为没有数据。

但是当我使用 JSON.stringify(obj) stringify 时,我得到:

{ _id: 53049728456d4416243bf65f,
user: 'patrice'
}

userCreatedstatus尚未字符串化,不会出现在我的输出中...

知道它来自哪里以及如何获取它吗?

我的模型是这样的:

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 通常不会删除空对象,因此这是 mongoose 特有的。

我建议尝试 .toObject() 或 .toJSON()

http://mongoosejs.com/docs/api.html#document_Document-toObject

这个将在 .stringify 期间被调用,所以它可能是删除空对象的东西。 http://mongoosejs.com/docs/api.html#document_Document-toJSON

所以先试试这个:

JSON.stringify(obj.toObject());

关于node.js - mongoose stringify 删除空元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22484340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com