2

I know I can do an update using $set:

Contact.update({
    _id: request.id
}, {
    $set: { name: newNameValue }
}, {
    upsert: false
}, function(err) { ... });

But in this case, instead of passing newNameValue, I'd like to use the previous name value to compute the new one. Let's say I want to capitalize the old name, something like:

Contact.update({
    _id: request.id
}, {
    $set: { name: $old.name.toUpperCase() }
}, {
    upsert: false
}, function(err) { ... });
Danziger
  • 19,628
  • 4
  • 53
  • 83
MarcoS
  • 17,323
  • 24
  • 96
  • 174

2 Answers2

2

I think this has already been answered here: How to add new data to current string in MongoDB?, so please, check that for a more detailed answer, but anyway, in short, you can't do that with a single query.

The way to do it using Mongoose, as shown in this official Mongoose example:

Contact.findById(request.id, (err, contract) => {
    if (err) return handleError(err);

    contract.name = contract.name.toUpperCase();

    contract.save((err, contractContract) => {
        if (err) return handleError(err);

        ...
    });
});
Danziger
  • 19,628
  • 4
  • 53
  • 83
0

as far as I know it's not possible. You would need to find and then update

Contact
    .find({
        _id: request.id
    })
    .exec(function(err, data) {
            if (err) {
                return ...;
            }
            Contact.findByIdAndUpdate(request.id, {
                $set: {
                    name: data.name.toUpperCase()
                }
            }, {
                new: true
            }, function(err, doc) {
                if (err) return ...;
                console.log(doc)
            });
        }
alfredopacino
  • 2,979
  • 9
  • 42
  • 68