你好!
因此,当我从数据库(JSON)请求一些数据时,它可以工作,但当尝试将数据推送到数据库中并将其发送回数据库时,它会显示以下内容:
[ { os: 'win32', sessionID: '18ef6ccf-4889-4fc6-a457-c235c5d5f16b' } ]
{ os: 'win32', sessionID: 'eb9feaf6-29c5-4481-b935-ade2ca3e82aa' }
2
为什么?
你能帮帮我吗?谢谢!
验证码:
let user = await this.usersModel.findOne({
username: data.username,
});
console.log(user)
let userSessions = await JSON.parse(user.sessions);
console.log(userSessions);
let newSessions = userSessions.push({
os: process.platform,
sessionID: sessionID,
});
console.log({
os: process.platform,
sessionID: sessionID,
});
console.log(newSessions);
await this.usersModel.findOneAndUpdate(
{
_id: user._id,
},
{
$set: {
sessions: JSON.stringify(newSessions),
},
}
);
用户集合(从MongoDB Compass导出):
[{
"_id": {
"$oid": "63a319a93e17b629d7bdd8f3"
},
"username": "Alms",
"password": "$2b$10$jVwFs6kc93ShowPhYXwCI.bTTJHvMZUyOOjw1hXOJGV/e0wQsDQa2",
"pfp": "default.png",
"created_at": "Wed Dec 21 2022 15:35:21 GMT+0100 (közép-európai téli idő)",
"__v": 0,
"notif": "[]",
"sessions": "2"
},{
"_id": {
"$oid": "63a355cd5568c9b72526a9fb"
},
"username": "Alms2",
"password": "$2b$10$pYXqp0DS952HLlD3E3LXs.Y89hoYOVV82HF1ibp7Y/9ptMpEYrXce",
"pfp": "default.png",
"created_at": "Wed Dec 21 2022 19:51:57 GMT+0100 (közép-európai téli idő)",
"__v": 0,
"notif": "[]",
"sessions": ""
},{
"_id": {
"$oid": "63a40c846b4dd1a7b08c51bb"
},
"username": "Alms3",
"password": "$2b$10$K8TU6FijRcVOTM4x6JVo5un21dxZht6JIUHMIvWMSV0SMmKqyT1Ra",
"pfp": "default.png",
"created_at": "Thu Dec 22 2022 08:51:32 GMT+0100 (közép-európai téli idő)",
"__v": 0,
"notif": "",
"sessions": ""
}]
a尝试的一切都在代码中。
1条答案
按热度按时间ogq8wdun1#
Array.push返回数组的新长度,而不是数组本身。
将userSessions变量初始化为数组
因此,在调用Array.push方法之后:
userSessions
将包含比userSessions
长1个元素的数组,newSessions
将包含userSessions
数组的长度。因此,当执行更新操作时,应该发送到数据库的值是
userSessions
: