简体   繁体   中英

Structuring my mongoDB for project and accessing nested arrays

This is how my DB structure currently looks: 在此处输入图像描述

Falafel is an account in my application, accounts in my application can hold their customer's data such as phone numbers, ip, country, and more. Banana is an example for a customer of Falafel. Whenever someone new registers as a customer of Falafel, I need to check if Falafel already has a customer with the same phone ( in order to prevent someone from registering two times ). This is my code as of now:

 Account.findOne({ userName: userName })
              .then((result) => {
                console.log(result.subs);
                Account.findOne({ phone: phone });
              })

              .then((result) => {
                if (result === null) {
                  console.log("Phone is available");}

Account.findOne finds the right document, in my example it finds the document which contains falafel and all of its information, including the "subs" array which has all the information of it's customers. As you see, in my code the problem starts in the fourth line "Account.findOne({phone: phone})" what I'm trying to do is to check if any of falafel's subscribers is holding the inserted phone number held in a variable named "phone". My first instinct was to type this:

Account.findOne({ result.subs.phone: phone })

but this did not work. What can I do about this issue? and is the structure of my DB even a good practice??

That is not a good design. Consider splitting your model into an Account collection and n Customer collection. Customer will reference the account it belongs to (just like a typical foreign key in a relational database).

Account:

{
  _id: ObjectId("1"),
  username: "user",
  pass: "pass", // at least hash and salt it pls
  desc: "desc"
}

Customer:

{
  _id: ObjectId("2"),
  accountId: ObjectId("1"),
  name: "banana"
}

Then use an aggregation pipeline to get your data. You will see that this model will make your life much easier and your application code much faster. Your current problem will also disappear.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM