简体   繁体   中英

Updating an object using mongoose

I'm trying to update an object inside my database using this code.

if (args[1] === 'set'){
            serverModel.findOneAndUpdate(
                {serverID: message.guild.id},
                {$set: {'restraints.channel': message.channel.id}}
            )
        }

The problem is that, while the code runs without error, nothing in the database has been updated.

It follows this model, yet I can't seem to update 'channel':

const serverSchema = new mongoose.Schema({
    serverID: {type: String, require: true, unique: true},
    restraints: {type: Object, require: true, default: {channel: null, locked: false, announce: null}}
});

serverModel.findOneAndUpdate() doesn't do anything other than return a Query .

A query needs to get executed before anything happens to your database.

There are various way to do that:

// preferred way:
await serverModel.findOneAndUpdate(…)

// OR, pass a callback:
serverModel.findOneAndUpdate(…, (err, doc) => { … })

// OR, just execute it and ignore the outcome:
serverModel.findOneAndUpdate(…).exec();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM