gpt4 book ai didi

javascript - 创建查询(连接)或更正设计?

转载 作者:可可西里 更新时间:2023-11-01 10:34:53 25 4
gpt4 key购买 nike

我在使用此设计构建一些简单查询时遇到问题。问题很简单,我想获取包含用户信息的帖子,这些信息应该都在一个数组中,这样我就可以将它传递给快速 View 。

简单,对我来说似乎错误的解决方案是在找到所有 posts(db.post.find({email:'mo@gmail.com'}) 然后循环遍历发布并进行一次查找查询哟用户集合,然后合并结果。

其他解决方案是使用 DBref 链接作者,这可能更好,但我还没有找到如何进行查询。

// User, the profile is not complete there will be more fields
var u = {
name: 'Michael', // Is not unique
email: 'mo@gmail.com', // Should be also unique
fbid: '4545454asdadsa'
}

db.user.insert(u);

// User can have 0 to many posts

var p = {
title: 'Suprise',
body: 'Well done',
tags: ['first', 'post', 'english'],
author: 'mo@gmail.com',
created: new Date(),
modified: new Date()
};
db.post.insert(p);

var p = {
title: 'Weather in Estonia',
body: 'Always looks bad',
tags: ['bad', 'weather', 'estonia'],
author: 'mo@gmail.com',
created: new Date(),
modified: new Date()
}
db.post.insert(p);

最佳答案

var p = {
title: 'Suprise',
body: 'Well done',
tags: ['first', 'post', 'english'],
author: {
name: 'Michael', // Is not unique
email: 'mo@gmail.com', // Should be also unique
fbid: '4545454asdadsa'
},
created: new Date(),
modified: new Date()
};

你嵌入文档,你反规范化。这就是它的工作原理。现在您只需获取所有帖子,而不必查询用户,因为他们已经存在。

数据结构

我会详细说明如何做到这一点。我对非规范化完全过分了。这意味着您永远不需要连接。请注意,如果其中一些只是多余且从不需要的,则可以将其删除。

帖子收集

{
title: String,
body: String,
tags: [String],
author: {
name: String,
email: String,
fbid: String
},
created: Date,
modified: Date,
comments: [{
body: String,
created: Date,
modified: Date
}]
}

用户合集

{ 
name: String,
email: String,
fbid: String,
posts: [{
title: String,
body: String,
tags: [String],
created: Date,
modified: Date,
comments: [{
body: String,
created: Date,
modified: Date
}]
}]
}

评论收集

{
body: String,
created: Date,
modified: Date,
author: {
name: String,
email: String,
fbid: String
},
post: {
title: String,
body: String,
tags: [String],
created: Date,
modified: Date
comments: [{
body: String,
created: Date,
modified: Date
}]
}
}

关于javascript - 创建查询(连接)或更正设计?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9530551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com