如何将对象数组保存到猫鼬数据库中

时间:2019-05-14 16:15:25

标签: node.js mongoose

我正在尝试保存由嵌套在数组中的对象制成的排行榜。我想将其保存在数据库中,但是我无法创建正确的架构,我不认为那是最好的方法。 当我运行代码时,出现以下错误:

“ LeaderBoardSchema不是构造函数”。

创建我需要的架构的适当方法是什么?

我已经尝试了许多在线查找的方法,但是我不断收到“ LeaderBoardSchema不是构造函数”的信息。

有关S.O的其他问题的示例对我没有太大帮助。

 
 
 // leaderboard object that i want to save
 leaderBoard = [
        leaderOne=   {
            name: 'Ultimate Beast',
            score: 2
        },
        leaderTwo=  {
            name: 'Masked Titan',
            score: 9
        },
        leaderThree=  {
            name: 'Oranolio',
            score: 7
        },
        leaderFour=  {
            name: 'Popularkiya',
            score:1
        },
        leaderFive=  {
            name: 'Bootecia',
            score: 11
        },
    ];




// Database schema 


const Schema = mongoose.Schema()

const LeaderBoardSchema = new mongoose.Schema({
   leaderBoard:{
    leaderOne :   {
        name: String,
        score: Number
    },
    leaderTwo :  {
        name: String,
        score: Number
    },
    leaderThree :  {
        name: String,
        score: Number
    },
    leaderFour :  {
        name: String,
        score:Number
    },
    leaderFive :  {
        name: String,
        score: Number
    }
   }
  }, {collection: 'leaderboard-data'});

const PlayerData = mongoose.model('LeaderBoard Data', LeaderBoardSchema);



// My attempt 


const leaderBoardToSave = new LeaderBoardSchema({
        leaderBoard:{
            leaderOne :   {
                name: 'asdf',
                score: 12
            },
            leaderTwo :  {
                name: 'sfgh',
                score: 12
            },
            leaderThree :  {
                name: 'weh',
                score: 12
            },
            leaderFour :  {
                name: 'asdf',
                score:12
            },
            leaderFive :  {
                name: 'asdf',
                score: 12
            }
        }
    })

1 个答案:

答案 0 :(得分:1)

当前,您的leaderBoard字段是一个对象。要对对象数组建模,请对您的架构执行以下操作:

const LeaderBoardSchema = new mongoose.Schema({
   leaderBoard: [
    {
        name: String,
        score: Number
    }
   ]
  }, {collection: 'leaderboard-data'});

关于架构构造函数的问题。您正在按照const PlayerData = mongoose.model('LeaderBoard Data', LeaderBoardSchema);创建猫鼬模型。但随后您执行new LeaderBoardSchema({...})。您需要改用猫鼬模型PlayerData。因此,创建一个新的页首横幅:

const leaderBoardToSave = new PlayerData({
        leaderBoard: [
           {
              name: 'asdf',
              score: 12
           },
           {
              name: 'gds',
              score: 12
           },
           {
              name: 'adad',
              score: 12
           },
       ]
    })