harmeet singh
harmeet singh

Reputation: 1

Update by id not does not change a field in Mongoose

I have a code in which I am making a new connection using Mongoose and using a schema also. The connection is made properly and I'm also getting the attributes from the collection. After that I want to update in my collection, and that is not working. I have following code

console.log("id : "+content._id); 
Alert.findByIdAndUpdate(content._id, {
    $set: {
        status: true
    }
}, function(error, result) {
    console.log(result);
    if (error) console.log(error);
    else {
        console.log('Alert updated');
    }
});

It shows alert updated but status remains false.

result for 1st console is 
id : 55096a5f91169c8e1673af20; 

and 2nd console is
Alert updated

Upvotes: 0

Views: 1756

Answers (2)

Gabriel Age
Gabriel Age

Reputation: 46

Your code looks perfect, the id looks like it's correct and your code don't return any errors, so have you checked your schema to see if it contains the "status" field?

Looks like you can create and edit new documents with a schema that is not equal on both sides, application an data layers.

More info here: https://github.com/Automattic/mongoose/issues/1060

Upvotes: 1

rxjmx
rxjmx

Reputation: 2181

Your code also looks right to me, maybe try one of the following?

Alert.findOne({_id : content._id}, function(error, alert) {
    if (error) console.log(error);
    alert.status = true;
    alert.save();
});

Or

 Alert.findOneAndUpdate({_id : content._id}, {
        $set: {
            status: true
        }
    }, function(error, result) {
        console.log(result);
        if (error) console.log(error);
        else {
            console.log('Alert updated');
        }
    });

Upvotes: 0

Related Questions