1

I made an account update with NodeJS and I want it to return for me the new updated values, because I need it on the client side. It consol logs undefined in jOk for the key values. What am I am doing wrong?

user.updateAccount = (jUserData, fCallback) => {
        var jUser = {
            userName: jUserData.txtEditAccountEmailorPhoneNumber,
            firstName: jUserData.txtEditAccountName,
            lastName: jUserData.txtEditAccountLastName,
            password: jUserData.txtEditAccountPassword,
            image: global.sUpdateUserImagePath
        }
        var userObjectId = global.mongoId(jUserData.txtEditAccountId)
        global.db.collection('users').updateOne({ "_id": userObjectId }, { $set: jUser }, (err, jResult) => {
            if (err) {
                var jError = { "status": "error", "message": "ERROR -> updateAccount -> user.js -> 001" }
                return fCallback(false, jError)
            }
            var jUserId = jResult._id
            var jNewUserRole = jResult.userRole
            var jNewUserName = jResult.userName
            var jNewUserFirstName = jResult.firstName
            var jNewUserLastName = jResult.lastName
            var jNewUserImage = jResult.image
            var jOk = {
                "status": "ok",
                "message": "user.js -> account updated -> 000",
                _id: jUserId,
                userRole: jNewUserRole,
                userName: jNewUserName,
                firstName: jNewUserFirstName,
                lastName: jNewUserLastName,
                image: jNewUserImage,
            }
            return fCallback(false, jOk)
        })
    }

My users table´s document structure in the db:

{
    "_id" : ObjectId("5a1a627f942bca5149ab3f25"),
    "userRole" : "admin",
    "userName" : "b@b.dk",
    "firstName" : "B",
    "lastName" : "B",
    "password" : "2",
    "image" : "public/img_webshop/fileUserImage-1511710009148.png"
}

Update with findOneAndUpdate(), where I added returnNewDocument: true. Still returns undefined. What am I doing wrong?

user.updateAccount = (jUserData, fCallback) => {
    var jUser = {
        userName: jUserData.txtEditAccountEmailorPhoneNumber,
        firstName: jUserData.txtEditAccountName,
        lastName: jUserData.txtEditAccountLastName,
        password: jUserData.txtEditAccountPassword,
        image: global.sUpdateUserImagePath
    }
    var userObjectId = global.mongoId(jUserData.txtEditAccountId)
    global.db.collection('users').findOneAndUpdate({ "_id": userObjectId }, { $set: jUser }, { returnNewDocument: true }, (err, jResult) => {
        if (err) {
            var jError = { "status": "error", "message": "ERROR -> updateAccount -> user.js -> 001" }
            return fCallback(false, jError)
        }
        var jUserId = jResult._id
        var jNewUserRole = jResult.userRole
        var jNewUserName = jResult.userName
        var jNewUserFirstName = jResult.firstName
        var jNewUserLastName = jResult.lastName
        var jNewUserImage = jResult.image
        var jOk = {
            "status": "ok",
            "message": "user.js -> account updated -> 000",
            _id: jUserId,
            userRole: jNewUserRole,
            userName: jNewUserName,
            firstName: jNewUserFirstName,
            lastName: jNewUserLastName,
            image: jNewUserImage,
        }
        return fCallback(false, jOk)
    })
}
codeDragon
  • 555
  • 1
  • 8
  • 28

2 Answers2

3

By default UpdateOne() doesn't return the updated item if you need the updated object then use findOneAndUpdate() instead

  • I just made an update with findOneAndUpdate(), where I added returnNewDocument: true. Still returns undefined. What am I doing wrong? – codeDragon Nov 26 '17 at 19:53
  • try this solution change returnNewDocument to returnOriginal and set it to false https://stackoverflow.com/a/35627439/5239892 – kingdynastyk Nov 26 '17 at 20:08
  • still returns undefined :( – codeDragon Nov 26 '17 at 20:12
  • check the _id you are giving to find the object. if both err and result are undefined that means the query ran successfully but couldn't find the object with given id – kingdynastyk Nov 26 '17 at 20:14
  • try also including upsert: true option – kingdynastyk Nov 26 '17 at 20:15
  • the update runs succesfully. this is what I get back: `{ status: 'ok', message: 'user.js -> account updated -> 000', _id: undefined, userRole: undefined, userName: undefined, firstName: undefined, lastName: undefined, image: undefined }` – codeDragon Nov 26 '17 at 20:20
  • 1
    what is the output of console.log(jResult) – kingdynastyk Nov 26 '17 at 20:24
  • interesting it gives me: `{ lastErrorObject: { updatedExisting: true, n: 1 }, value: { _id: 5a1a627f942bca5149ab3f25, userRole: 'admin', userName: 'a@a.dk', firstName: 'A', lastName: 'A', password: '1', image: 'public/img_webshop/fileUserImage-1511728628498.png' }, ok: 1 }` – codeDragon Nov 26 '17 at 20:40
  • so probably I need to add `.value` after jResult when I am asking for each field? – codeDragon Nov 26 '17 at 20:41
  • yup that's it :) – kingdynastyk Nov 26 '17 at 20:44
  • huh thank´s it finally works, I did a `findOne()`before where just `jResult.field` worked, and I applied the same logic here, but I totally forgot about that the result is different according to each method – codeDragon Nov 26 '17 at 20:54
0

Let's take an example.

const filter = { name: 'Jean-Luc Picard' };
const update = { age: 59 };
let doc = await Character.findOneAndUpdate(filter, update, {
  new: true
});
doc.name; // 'Jean-Luc Picard'
doc.age; // 59`

You should **set the new option to true to return the document** after the update was applied.

So what happens is that it finds the document matching the filter -> updates the first matched document -> returns the updated document. If it does not finds the document matching the filter it will create one if let options = {upsert: true} is provided as the third parameter in findOneAndUpdate(filter, update, options)

You can refer to this doc [Mongoosex5.7.13: findOneAndUpdate()][1]. [1]: https://mongoosejs.com/docs/tutorials/findoneandupdate.html

Jay
  • 674
  • 11
  • 13