简体   繁体   English

如何使用 mongoose 为已创建的文档编写子文档

[英]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".用户已经创建,我只需要填写“lolDataSchema”中的信息。 For that, I've tried with this function, but when I look at the db, the data wasn't saved.为此,我尝试过使用这个 function,但是当我查看数据库时,数据没有保存。 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 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