[英]Get collection by user id in MongoDB
The biggest problem is I'm totally new to MongoDB
.最大的问题是我对
MongoDB
完全MongoDB
。 I know how to do it in SQL
but am unable to shift my thinking into NoSQL
.我知道如何在
SQL
做到这一点,但无法将我的想法转移到NoSQL
。 I have this model:我有这个模型:
var accountSchema = new mongoose.Schema({
isPremium: Boolean,
website: []
});
I'm using mongoose so it creates Id, username, and password automatically.我正在使用猫鼬,因此它会自动创建 ID、用户名和密码。 My registered user looks like this:
我的注册用户如下所示:
{
_id: ObjectId('5a79c89b59b6042a5d89584b'),
websites: ['a.com', 'b.com', 'c.com'],
username: 'a@a.a',
isPremium: false,
hash:
'a long hash',
salt: 'a long salt',
__v: 0,
};
I want want to write out the websites
array.我想写出
websites
数组。 I want to grab only the websites under a certain user.我只想抓取某个用户下的网站。 (Don't want others to just see all websites).
(不希望其他人只看到所有网站)。
How would I do it?我该怎么做? Would I pass the userId after a click or make it in a session?
我会在单击后传递 userId 还是在会话中进行传递? And would the 'query' look like?
“查询”会是什么样子?
You can do it like this.你可以这样做。
First define your model as a separate module首先将您的模型定义为一个单独的模块
var mongoose = require('mongoose');
const accountSchema = mongoose.Schema(
{
isPremium: Boolean,
website: []
});
module.exports = mongoose.model('account',accountSchema);
Then you can use this model everywhere in your code然后你可以在你的代码中到处使用这个模型
const account = require('yourModulePath');
account.findOne({YouSearchParameters}).
then((account) => {
// let websites = account.website
// Do you logic
})
You also can filter result with .select您还可以使用 .select 过滤结果
account.findOne({YouSearchParameters}).select({ "website": 1, "_id": 0}).then((account)
So you will just get your array of websites所以你只会得到你的网站数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.