简体   繁体   中英

Updating a model in anguler (mongoose/mongodb) specifically an array of objects that is an attribute of the model

I have the following schema:


   const AuthorSchema = new mongoose.Schema({
        fullName: { type: String, required: [true, "Authors must have a full name"], minlength: [6, "Author's full name must have at least 6 characters"] },
        quotes: [{content: {type: String, minlength: [6, "Quotes should be six characters"]}, vote: {type: Number, default: 0}}],
    }, { timestamps: true });
const Author = mongoose.model('Author', AuthorSchema);
module.exports = Author

And I am trying to update the "vote" in a particular "quote" using this in my controller:

    upvote: function(req, res) {

        console.log("UPVOTE_CONTROLLER", req.body);
        var author = Author.findOne({_id: req.body.authid})
        .then(author =>{ (console.log(author))
            let quotes = author.quotes;
            for (var key in quotes){
                if (key._id == req.body.quoteid){
                    key.vote = key.vote + 1;
                    console.log("**UPDATED_QUOTE_BEFORE_SAVE", key)
                    return key.save();
                }
            }
        })
        .then(saveresult => res.json(saveresult))
        .catch(err => {
            console.log("****ERRROR HERE****");
            console.log(err);
            for (var key in err.errors) {
                req.flash('registration', err.errors[key].message);
            }
            res.json({errors: err.errors});
        });
    },

I get into all the way into the controller method, no errors are thrown, but the for loop never seems to run,

I have tried many different ways of changing the vote ex. key.vote += 1; key.vote +1; etc I have tried saving the entire author not just the specific quote that is represented by key.

The "challenge" on this project is to do this using only a single schema, so I cannot use the normal Quote.findOne({_id: request.body.id}) as there is no Quote schema.

any help here would be appreciated.

I figured it out:

In the for loop it should have been for ( let key OF quotes){ instead of IN.

Other changes after the for loop ran:

key.note += save;

author.save(); instead of key.save();

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