简体   繁体   中英

How to write subdocuments for an already created document with mongoose

I've created this Schema:

const lolDataSchema = new mongoose.Schema({
    userId:{type: mongoose.Schema.Types.ObjectId , ref:'User'},
    id: {type: String},
    name: {type: String},
    accountId: {type: String},
    puuid: {type: String, unique:true},
    lolServer: {type: String},
    summonerLevel: {type:Number},
})

const UserSchema = new mongoose.Schema({
    username: {type: String, require: true, unique:true},
    email: {type: String, require: true, lowercase: true, unique:true},
    password: {type:String, require: true, select: false},
    createdAt: {type: Date, default: Date.now},
    LolData: lolDataSchema
});

The user was already created, I just need to fill the info from the "lolDataSchema". For that, I've tried with this function, but when I look at the db, the data wasn't saved. What i'm doing wrong?

module.exports = {
    async saveSummoner(req, res) {
        const lolDataApi = await axios.get(`https://${server}.api.riotgames.com/lol/summoner/v4/summoners/by-name/${req.body.name}?api_key=${api_key}`).catch(error => console.log(error));
        User.findOneAndUpdate(req.body._id, { $push: {LolData: lolDataApi.data} } );
        console.log(lolDataApi.data);
        return res.json(lolDataApi.data);
        }

}

findOneAndUpdate doesn't not return the new updated document instead it returns the original by defaults if you are using mongodb use {new:true} if you are using mongoose use instead {returnOriginal:false} try and us this

User.findOneAndUpdate(req.body._id, { $push: {LolData: lolDataApi.data}},{returnOriginal:false}, (err, doc) => {
        if (err) {
            console.log("error while updating");
        }
        console.log(doc);
    });  

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