MongoDB doesn't return document when searching for field with _id from another collection

Question

I have two collections:

users
nameHistory

Everytime a user is changing username, I store that as a document in the nameHistory collection. The documents get a field named userId with the value of the _id in the users table.

To find the name history of a user (all documents in the nameHistory collection with the userId equal to the _id I use this method:

exports.getNameHistory = (_id, callback) => {
    mongodb.connect(mongodbUrl, (error, database) => {
        if (error) {
            console.log('[Database] getNameHistory() Error connecting: ' + error)
            callback('Failed to connect.', undefined)
            return
        }
        const query = { userId: _id }
        database.collection('nameHistory').find(query).toArray((error, nameHistory) => {
            if (error) {
                console.log('[Database] getNameHistory() Error finding: ' + error)
                callback('Failed to find.', undefined)
                return
            }
            database.close()
            callback(undefined, nameHistory)
        })
    })
}

I also tried find with an empty query, just to see if the document was actually saved. It was saved with the correct value for the userId field. In addition, I logged the _id parameter and it was correct.

I don't get any errors, it just returns an empty array. Do you have any suggestions to why it doesn't find the document?


Show source
| find   | node.js   | mongodb   | collections   2017-10-09 20:10 0 Answers

Answers to MongoDB doesn't return document when searching for field with _id from another collection ( 0 )

Leave a reply to - MongoDB doesn't return document when searching for field with _id from another collection

◀ Go back