jmls
jmls

Reputation: 2969

mongoose , node and asynchronous coding howto

Ok, I need my lightbulb switching on. I have been struggling with this for nearly a week now, and just get more and more confused.

I have these collections:

Customers
Orders (linked to Customer by Customer_id)
OrderLines (linked to Order by Order_id)
Salesreps (linked to Customer by Customer_id)

I do not have any embedded documents.

What I want to do is to get a string of data comprising of the following:

Customer_1

Order#1:First_OrderLine_of_Order_Number
Order#n:First_OrderLine_of_Order_Number

SalesRep_of_Customer_Name

...

Customer_n

Order#1:First_OrderLine_of_Order_Number
Order#n:First_OrderLine_of_Order_Number

SalesRep_of_Customer_Name

Could someone give me pseudo-code to explain how to do this in node and mongoose? I need to be taught how to fish ;)

Upvotes: 0

Views: 236

Answers (2)

JohnnyHK
JohnnyHK

Reputation: 311835

It's very easy to get frustrated and confused, especially when you try and learn more than one thing at a time. Don't just hack around trying to get stuff to work; start at the bottom and work your way up the stack. Resist the temptation to move on to the next layer until you fully understand the layer it depends upon.

  1. JavaScript
  2. Node.js
  3. MongoDB
  4. Mongoose

You'll learn your forEach skills in step 1, your async callback skills in step 2, you'll understand how to find your documents in step 3, and you'll put it all together in step 4. There's no shortcut if you truly want to 'learn to fish'.

Upvotes: 2

LoG
LoG

Reputation: 1141

When dealing with NoSQL (a really bad name for the technology) you must setup your datasets in a different way.

In mongo you don't have joins, so you'll have to refactor your data. Think in embedded documents when you can (orders with embedded order lines for instance).

I'd use something like this:

Order: {
  _id: ObjectId
, user: DBRef // (or ObjectId)
, lines: [
    {foo: "bar"}
  , ...
  ]
}

User: {
  _id: ObjectId
, salesref: { _id: ObjectId, name: "James Brown"}
, more_data ...
}

SalesRef: {
  _id: ObjectId
, more_data...
}

Keeping a minimal reference to the referenced collection, you could even add an user: {name: "Max Power", sales: "James Brown"} inside your order but keep in mind that you will need to keep it consistent by hand during the document modification/insertion.

Upvotes: 0

Related Questions