如何在 NodeJS 模式中定义对象?
我目前有一个这样的模式:
const postSchema = mongoose.Schema({
title: String,
message: String,
name: String,
creator: String,
tags: [String],
selectedFile: String,
likes: { type: [String], default: [] },
createdAt: {
type: Date,
default: new Date(),
},
})
我预计的问题之一是,随着用户数量的增长,搜索喜欢数组将变得低效。有没有一种方法可以将 Likes 数组存储为对象(键是 userId,值可以是 true),以便在对象中查找某人会变得更有效。
我也愿意听取您可能有的任何其他想法。
谢谢!
I currently have a schema like this:
const postSchema = mongoose.Schema({
title: String,
message: String,
name: String,
creator: String,
tags: [String],
selectedFile: String,
likes: { type: [String], default: [] },
createdAt: {
type: Date,
default: new Date(),
},
})
One of the problem that I anticipate is that as the number of users grow, searching the likes array will become inefficient. Is there a way to store the likes array instead as an Object (key would be userId and value could be true) so that finding someone in the Object would become more efficient.
I am also open to hearing any other ideas that you might have.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想为此建议 populate() 。由此,您可以管理一个大号。用户信息没有问题。您可以创建一个新的 schema 作为 Likes,并将 Likes 文档的 id 添加为带有 populate 的 id。检查下面的例子。
然后创建如下所示的 postschema。
您可以通过在运行如下查询时进行填充来轻松获取点赞文档中的所有数据。
检查 填充 和 population 部分以了解更多信息。
I want to suggest populate() for this. From that, you can manage a large no. of user information without a problem. You can create a new schema as likes and add the id of the likes document as an id with the populate. Check the below example.
Then create the postschema like below.
You can easily get all the data inside a likes document by populating when running a query like below.
Check the populate and population sections of the mongoose documentation to learn more.