Search code examples
javascriptnode.jsmongodbobjectspread-syntax

spread object and add flag node.js


Here is my code:

let collection = database.collection('documents')
let savedDocumentsCollection = database.collection('savedDocuments')
let doc = await collection.find().toArray()
let saved_documents = await savedDocumentsCollection.find({username: req.session.username}).toArray()

let document_ids = []
for (var i = 0; i < doc.length; i++) {
  document_ids.push(doc[i].id)
}

for (var x = 0; x < saved_documents.length; x++) {
  for(let val of document_ids) {
    if (val == saved_documents[x].id) {
        doc = {
          ...doc,
          saved: true
        }
        // console.log(true)
      } else {
        doc = {
          ...doc,
          saved: false
        }
        // console.log(false)
    }
  }
}

console.log(doc)

to sum it up, what it does it get the data inside collection documents and savedDocuments. What I am trying to do is compare the id's of both collections to each other, and if they both exist, then spread the current doc object and add the flag saved: true to it, and if it doesn't exist in savedDocuments then add flag saved: false to it. However, when I log console.log(doc), my results look like this:

    '0': {
    _id: new ObjectId("635f3c3d79dffde472e69287"),
    course_code: 'xxxxx',
    name_of_document: 'doc 1',
    name_of_s: 'COMPANY',
    url: 'url',
    uploadedBy: '[email protected]',
    date: 2022-10-31T03:08:45.123Z,
    id: '2ac3c'
  },
  '1': {
    course_code: 'xxxxx',
    name_of_document: 'doc 2',
    name_of_s: 'COMPANY',
    url: 'url',
    uploadedBy: '[email protected]',
    date: 2022-10-31T03:14:40.722Z,
    id: 'fursr'
  },
  saved: false
}

as you can see, it only adds one saved: false flag there, not even within the doc root. There is about 10 documents in there that you don't see here, so rest assured about 5 have matching id's, and you can see I tested it by logging true or false as well, and watched it happen live. What am I doing wrong?


Solution

  • The following code constructs a Set containing the ids of the saved documents, enabling constant-time checking whether a given ID is saved.

    The code then enumerates all the documents and configures the saved property according to presence in the Set.

    Time complexity is therefore O(N).

    Does this do what you want?

    let allDocuments = [{ id: '0', name: 'foo' }, { id: '1', name: 'bar' }]
    let savedDocuments = [{ id: '1' }]
    
    const addSavedMetadata = (all, saved) => {
      const savedSet = saved.reduce((acc, {id}) => acc.add(id), new Set)
      all.forEach((d) => d.saved = savedSet.has(d.id))
      return all
    }
    
    console.log(addSavedMetadata(allDocuments, savedDocuments))