Home > database >  NestJS and Mongoose Not working as expected
NestJS and Mongoose Not working as expected

Time:12-27

Hello!

So, so when i request some data from the database (JSON), it works, but when a try to push data in it and send it back to the database, then it gives me this:

[ { os: 'win32', sessionID: '18ef6ccf-4889-4fc6-a457-c235c5d5f16b' } ]
{ os: 'win32', sessionID: 'eb9feaf6-29c5-4481-b935-ade2ca3e82aa' }
2

Why?

Can you help me? Thanks!

Heres the code:

          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),
              },
            }
          );

Users collection (Exported from 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": ""
}]

Everything a tried is in the code.

CodePudding user response:

Array.push returns the new length of the array, not the array itself.

You initialize the userSessions variable to an array

let userSessions = await JSON.parse(user.sessions)

So after you invoke the Array.push method:

let newSessions = userSessions.push({
            os: process.platform,
            sessionID: sessionID,
          })

userSessions will contain an array that is now 1 element longer, and newSessions will contain the length of the userSessions array.

So when you get to the update operation, the value you should be sending to the database is userSessions:

              $set: {
                sessions: JSON.stringify(userSessions),
              }
  • Related