gpt4 book ai didi

javascript - Mongoose + Node.js,Object.assign(从数据库返回的数据的副本)显示附加数据

转载 作者:可可西里 更新时间:2023-11-01 09:13:23 25 4
gpt4 key购买 nike

今天我发现了一个有趣的事情,这是我以前不知道的。我需要帮助来理解为什么会这样:

User.findOne({email: req.body.email}, function(err, usr){
return res.json({
RAW: usr,
COPY: Object.assign({}, usr, {some: 'change'})
})
})

这个产量

{
"RAW": {
"createdAt": "2018-06-25T09:16:35.516Z",
"_id": "5b30b2f36c492c55a818b455",
"email": "some@email.com",
"password": "$2b$08$k5IRBF.1i.q.7D/BD4HCVuOdnIRDQOHaT6icNwIyc1XfeklUwyF5.",
"__v": 0
},
"COPY": {
"$__": {
"strictMode": true,
"selected": {},
"getters": {},
"_id": "5b30b2f36c492c55a818b455",
"wasPopulated": false,
"activePaths": {
"paths": {
"createdAt": "init",
"_id": "init",
"email": "init",
"password": "init",
"__v": "init"
},
"states": {
"ignore": {},
"default": {},
"init": {
"_id": true,
"email": true,
"password": true,
"createdAt": true,
"__v": true
},
"modify": {},
"require": {}
},
"stateNames": [
"require",
"modify",
"init",
"default",
"ignore"
]
},
"pathsToScopes": {},
"emitter": {
"domain": null,
"_events": {},
"_eventsCount": 0,
"_maxListeners": 0
},
"$options": true
},
"isNew": false,
"_doc": {
"createdAt": "2018-06-25T09:16:35.516Z",
"_id": "5b30b2f36c492c55a818b455",
"email": "some@email.com",
"password": "$2b$08$k5IRBF.1i.q.7D/BD4HCVuOdnIRDQOHaT6icNwIyc1XfeklUwyF5.",
"__v": 0
},
"$init": true,
"some": "change"
}
}

查看RAWCOPY 之间的区别。据我了解

  1. Object.assign() 只是用新的内存地址创建对象的副本。
  2. 然后 RAW.email 应该等于 COPY.email(但不是,为什么?)

显然,COPY 包含来自 MongoDB 的信息,如果 RAW 已经有这些数据(隐藏),那么 RAW.email 如何获取数据,而 COPY.emailundefined

这种抽象如何在 RAW 的情况下工作?

最佳答案

作为Express res.json documentation州,

Sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using JSON.stringify().

JSON.stringify 使用 toJSON method可用于获取对象值的地方。 Mongoose 文档 support it .

由于 toJSON 不是 usr 自己的可枚举方法,所以在用 Object.assign({}, usr) 浅拷贝时省略>,因此该对象被 JSON.stringify 原样处理,并且公开了内部文档属性。

它可能应该是:

 res.json({
RAW: usr,
COPY: Object.assign({}, usr.toJSON(), {some: 'change'})
})

关于javascript - Mongoose + Node.js,Object.assign(从数据库返回的数据的副本)显示附加数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51021542/

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