我正在使用 mongoose 和 node.js,这是一个简单的架构
const addressSchema = new mongoose.Schema({
address: String,
region: String,
fullArea: Array,
},{
timestamps: true,
versionKey: false,
toObject: {
virtuals: true,
getters: true,
transform: (_, ret) => {
ret.id = ret._id;
delete ret._id;
}
},
})
我使用 toObject() 来返回带有 id 而不是 _id 的数据对象。
const alls = await addressModel
.find(query)
.skip(skip)
.limit(limit)
.exec();
console.log( alls );
在服务器端的控制台中打印时,我看到数据对象具有 id 而不是 _id。
[
{
....
__v: 0,
id: new ObjectId('6645b78ade005ba6ca47310e')
}
]
但是当express服务器将相同的数据发送回客户端时, res.status(StatusCodes.OK).json( data );
客户端收到的最终数据始终具有_id,而不是预期的id
{
"data":[
{ "_id":"6645b78ade005ba6ca47310e",....}
]
}
发生了什么 ?
您需要改用 toJSON 帮助器: