Alex Ironside
Alex Ironside

Reputation: 5039

Get collection by user id in MongoDB

The biggest problem is I'm totally new to MongoDB. I know how to do it in SQL but am unable to shift my thinking into 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. My registered user looks like this:

{
  _id: ObjectId('5a79c89b59b6042a5d89584b'),
  websites: ['a.com', 'b.com', 'c.com'],
  username: '[email protected]',
  isPremium: false,
  hash:
    'a long hash',
  salt: 'a long salt',
  __v: 0,
};

I want want to write out the websites array. 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? And would the 'query' look like?

Upvotes: 1

Views: 184

Answers (1)

Vitaly Migunov
Vitaly Migunov

Reputation: 4457

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

account.findOne({YouSearchParameters}).select({ "website": 1, "_id": 0}).then((account)

So you will just get your array of websites

Upvotes: 1

Related Questions