这是故事:NodeJS的新手>尝试使用mongoose>播种mongoDB数据库需要帮助。
我有两个系列:用户(或玩家)和团队。 种子目标:创建一些用户,然后创建一些团队,其中包含一些用户。
这是我的用户架构:
var mongoose = require('mongoose');
var passportLocalMongoose = require('passport-local-mongoose');
var UserSchema = new mongoose.Schema({
name: String,
username: String,
password: String
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);
这是我的团队架构:
var mongoose = require('mongoose');
var passportLocalMongoose = require('passport-local-mongoose');
var TeamSchema = new mongoose.Schema({
name: String,
users: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}
]
});
TeamSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("Team", TeamSchema);
这是播种尝试:
var mongoose = require('mongoose');
function seed(collectionName, data, schema){
schema.remove({}, function(err){
if(err){
console.log(collectionName + ".remove: " + err);
} else {
console.log("All " + collectionName + " collection removed");
data.forEach(function(dt){
schema.create(dt, function(err, newData){
if(err){
console.log(collectionName + ".create: " + err);
} else {
console.log(collectionName + " added: " + newData.name);
}
});
});
}
});
}
function seedDB(){
var userData = require('./data/userData'),
userSchema = require('../../models/user');
seed("User", userData, userSchema);
var teamData = require('./data/teamData'),
teamSchema = require('../../models/team');
seed("Team", teamData, teamSchema);
};
module.exports = seedDB;
是的,我试图封装种子函数,所以我可以在每个我想要播种的集合中使用它(事实上,我相信这是问题所在。)
的UserData:
module.exports = [
{
name: "Name1",
username: "nickname1",
password: "pass"
},
{
name: "Name2",
username: "nickname2",
password: "pass"
}
];
teamData:
module.exports = [
{
name: "Team1",
users: [
{ "_id" : "594497aa0a403b183ce7e485", "name" : "Name1", "username" : "nickname1", "password" : "pass", "__v" : 0 },
{ "_id" : "594497aa0a403b183ce7e486", "name" : "Name2", "username" : "nickname2", "password" : "pass", "__v" : 0 }
]
},
{
name: "Team 2",
users: [
{ "_id" : "594497aa0a403b183ce7e485", "name" : "Name1", "username" : "nickname1", "password" : "pass", "__v" : 0 }
]
}
];
当我运行 seed()时,我收到以下错误消息:
Team.create: WriteError({"code":11000,"index":0,"errmsg":"E11000 duplicate key error collection: pastinha2.teams index: username_1 dup key: { : null }","op":{"name":"Team 2","_id":"5944afd68157e62190ec1919","users":["594497aa0a403b183ce7e485"],"__v":0}})
据我所知,问题是正在执行的命令,因为查询调用是异步的。不确定这是否真的是问题,但如果是,我该如何防止它发生?
很抱歉这篇文章很长,但我找到了几个类似问题的主题,我仍然真的被困在这里。可以使用一些帮助。 提前谢谢。