save()后具有嵌套对象模型的重复种子条目

时间:2017-09-04 17:38:42

标签: javascript node.js mongodb mongoose

种子功能在traits数组中创建重复的条目。

var seedGenres = () => {
  seedData.genres.forEach((seed) => {
    Genre.create({
      name: seed.name
    }, (err, newGenre) => {
      if (err) {
        console.log(err)
      } else{
        console.log("Genre Created")
        seed.traits.forEach((trait) => {
          Trait.create({
            name: trait.name,
            upvoteScore: 0,
            downvoteScore: 0,
            totalVotes: 0
          }, (err, newTrait) => {
            if (err) {
              console.log(err, newTrait)
            } else {
              newGenre.traits.push(newTrait)
              newGenre.save()
              console.log(newGenre.traits)
              console.log('Trait pushed succesffuly')
            }
          })
        })
      }
    })
  })
}

Genre.model.js

const mongoose = require('mongoose')

var genreSchema = new mongoose.Schema({
  name: String,
  traits: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Trait"
    }
  ]
})

module.exports = mongoose.model("Genre", genreSchema)

Trait.model.js

const mongoose = require('mongoose')

var traitSchema = new mongoose.Schema({
  name: String,
  upvoteScore: Number,
  downvoteScore: Number,
  totalVotes: Number
})

module.exports = mongoose.model("Trait", traitSchema)

基本上我们想要播放一些具有3个特征的类型,当控制台记录它正在做的事情时,它似乎是正确的。但是,在完成运行后查看集合时,每种类型下有6个特征条目(我们期望的两倍)

这就是我们所期待的

{     “_id”:ObjectId(“59ad8a73fa7058a4dc9c4971”),     “名字”:“RPG”,     “特质”:[         的ObjectId( “59ad8a73fa7058a4dc9c4974”),         的ObjectId( “59ad8a73fa7058a4dc9c4975”),         的ObjectId( “59ad8a73fa7058a4dc9c4973”)     ]     “__v”:3 }

这是我们目前获得的输出。

{     “_id”:ObjectId(“59ad8a73fa7058a4dc9c4971”),     “名字”:“RPG”,     “特质”:[         的ObjectId( “59ad8a73fa7058a4dc9c4974”),         的ObjectId( “59ad8a73fa7058a4dc9c4974”),         的ObjectId( “59ad8a73fa7058a4dc9c4975”),         的ObjectId( “59ad8a73fa7058a4dc9c4974”),         的ObjectId( “59ad8a73fa7058a4dc9c4975”),         的ObjectId( “59ad8a73fa7058a4dc9c4973”)     ]     “__v”:3 }

1 个答案:

答案 0 :(得分:0)

我打赌你将同步for循环与异步Mongoose操作混合在一起。

我的第一个建议是将push更改为addToSet()

我的第二个建议是使用async.js

async.mapSeries(seedData.genres, (seed, cb1) => {
    Genre.create({ name: seed.name }, (err, newGenre) => {
        // stop mapSeries() if an error occurs
        if (err) return cb1(err);

        console.log("Genre Created")

        // create traits
        async.eachSeries(seed.traits, (trait, cb2) => {
            Trait.create({ name: trait.name, upvoteScore: 0, downvoteScore: 0, totalVotes: 0 }, (err, newTrait) => {
                // stop eachSeries() if an error occurs
                if (err) return cb2(err);

                console.log("Trait Created")

                // add trait to genre
                newGenre.traits.push(newTrait);
                // mark current async task as done
                cb2();
            });
        }, err => {
            // if an error occurred during eachSeries()
            if (err) return cb1(err);
            // otherwise, save the genre
            newGenre.save(cb1);
        });
    })
}, (err, genres) => {
    // if an error occurred during the operations, it will come here
    if (err) {
        console.log(err);
        return;
    }
    console.log('DONE!', genres);
});