通过猫鼬引用 MongoDB 的正确方法



我有三个模式,一个引用另外两个:

用户架构

{ name: String }

后架构

{ content: String }

注释架构

{ 
content: String,
user: { ObjectID, ref: 'User' },
post: { ObjectID, ref: 'Post' }
}

如何以合理、可扩展的方式为此数据库设定种子?即使使用蓝鸟承诺,它很快就会成为写作的噩梦。

到目前为止,我的尝试涉及多个嵌套承诺,并且很难维护:

User
.create([{ name: 'alice' }])
.then(() => {
return Post.create([{ content: 'foo' }])
})
.then(() => {
User.find().then(users => {
Post.find().then(posts => {
// `users` isn't even *available* here!
Comment.create({ content: 'bar', user: users[0], post: posts[0] })
})
})
})

这显然不是这样做的正确方法。我错过了什么?

不确定蓝鸟,但nodejs Promise.all应该完成这项工作:

Promise.all([
User.create([{ name: 'alice' }]),
Post.create([{ content: 'foo' }])
]).then(([users, posts]) => {
const comments = [
{ content: 'bar', user: users[0], post: posts[0] }
];    
return Comment.create(comments);
})

如果要使用自动引用为数据库设定种子,请使用 Seedgoose。 这是您最容易使用的播种机。您不需要编写任何程序文件,而只需要写入数据文件。Seedgoose为您处理智能参考。顺便说一下,我是这个包的作者和维护者。

试试这个它会正常工作:

注意:Node Promise.all 将确保两个查询都正确执行,然后在 Array:[Users, Posts] 中返回结果, 如果您在执行任何查询期间收到任何错误,它将由 Promise.all 的 catch 块处理。

let queryArray = [];
queryArray.push(User.create([{ name: 'alice' }]));
queryArray.push(Post.create([{ content: 'foo' }]));
Promise.all(queryArray).then(([Users, Posts]) => {
const comments = [
{ content: 'bar', user: Users[0], post: posts[0] }
];   
return Comment.create(comments);
}).catch(Error => {
console.log("Error: ", Error);
})

最新更新