OSMX
OSMX

Reputation: 45

How to update a value inside mongodb with nodeJS?

I'm trying to update a value inside mogoodb array but is the problem database?

    "TempChannels": [{
        "user": "299481590445113345",
        "channel": "794869948878159884",
        "settings": []
    }, {
        "user": "583363766750806043",
        "channel": "795004103998308352",
        "settings": []
    }],

The part of the code that should update the user:

Data.TempChannels[0].user = Target.id
Data.save().catch(er => console.log(er))

Also, no error appears when I run the code. and when i console the data it returns a user which has updated but it is not actually saved in mongodb! code

Data.save().then(() => console.log(Data.TempChannels[0].user))

this is the whole data

{
    "_id": {
        "$oid": "5ff0cd1ee3d9fd2d40d82d23"
    },
    "TempChannels": [{
        "user": "299481590445113345",
        "channel": "795014692522295326",
        "settings": []
    }, {
        "user": "583363766750806043",
        "channel": "795015273060892753",
        "settings": []
    }],
    "Guild": "704158258201624657",
    "Stats": "true",
    "ChannelID": "795014681664290826",
    "ParentID": "795014680556994610",
    "LogChannelID": "795014683601010709",
    "TempControlChannelID": "795014682518749274",
    "DefaultSettings": {
        "limit": null,
        "name": null,
        "bitrate": null,
        "copyperms": null
    },
    "__v": 2
}

I'm filtering the data by Guild

Upvotes: 1

Views: 177

Answers (3)

shubham kumar
shubham kumar

Reputation: 91

if you are using mongoose to connect MongoDB, the 
Use markModified("updated field name")

Data.TempChannels[0].user = Target.id
Data.markModified('TempChannels');
Data.save().catch(er => console.log(er))

Upvotes: 2

Ahmed Abdallah
Ahmed Abdallah

Reputation: 51

If you are using Mongoose, you can update the record by doing something similar to this:

SchemaName.update({Guild: 'Guild Value Here'}, {$set: { "TempChannels[0].user" : "%newvalue%"}})
.then((data) => {
    console.log(data)
})
.catch(err => {
    console.log.error(err);
    
});

You should replace schemaName with the name of your schema if you are using mongoose, and in case you are not using it, I think it would be better for you to start using it.

Upvotes: 0

iiSam
iiSam

Reputation: 81

if you are using mongoose, there is a method that will allow to update the content of existing data

const res = await Person.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' });
res.n; // Number of documents matched
res.nModified; // Number of documents modified

Upvotes: 0

Related Questions