![](/img/trans.png)
[英]How to get data from a separate collection and join it with a user collection without having a same common id to link both of them in MongoDB?
[英]Get collection by user id in MongoDB
最大的问题是我对MongoDB
完全MongoDB
。 我知道如何在SQL
做到这一点,但无法将我的想法转移到NoSQL
。 我有这个模型:
var accountSchema = new mongoose.Schema({
isPremium: Boolean,
website: []
});
我正在使用猫鼬,因此它会自动创建 ID、用户名和密码。 我的注册用户如下所示:
{
_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,
};
我想写出websites
数组。 我只想抓取某个用户下的网站。 (不希望其他人只看到所有网站)。
我该怎么做? 我会在单击后传递 userId 还是在会话中进行传递? “查询”会是什么样子?
你可以这样做。
首先将您的模型定义为一个单独的模块
var mongoose = require('mongoose');
const accountSchema = mongoose.Schema(
{
isPremium: Boolean,
website: []
});
module.exports = mongoose.model('account',accountSchema);
然后你可以在你的代码中到处使用这个模型
const account = require('yourModulePath');
account.findOne({YouSearchParameters}).
then((account) => {
// let websites = account.website
// Do you logic
})
您还可以使用 .select 过滤结果
account.findOne({YouSearchParameters}).select({ "website": 1, "_id": 0}).then((account)
所以你只会得到你的网站数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.