簡體   English   中英

如何使用 mongoose 為已創建的文檔編寫子文檔

[英]How to write subdocuments for an already created document with mongoose

我創建了這個架構:

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
});

用戶已經創建,我只需要填寫“lolDataSchema”中的信息。 為此,我嘗試過使用這個 function,但是當我查看數據庫時,數據沒有保存。 我做錯了什么?

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 不會返回新的更新文檔,而是默認返回原始文檔,如果您使用的是 mongodb,請使用{new:true}如果您使用的是 mongoose,請改用{returnOriginal:false}試試這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM