[英]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.