1

I have a users model with a ref to company. My data is as follows:

{
"name":"justin", 
"notes":"hello notes",
"company":
    {"name":"acme inc"}
}

Is it possible to save my data as a single call or would I need to save my company model first, then save my user afterward?

var UserSchema = new Schema({
    name: {
        type: String,
        trim: true,
        default: ''
    },
    notes:{
        type:String
    },
    company: {
        type: Schema.ObjectId,
        ref: 'Company'
    })
Justin Young
  • 2,393
  • 3
  • 36
  • 62

1 Answers1

1

In a NoSQL database everything is document oriented so you wouldn't typically do what you are trying to do. You will need to manage the "foreign key" relationship yourself, in code.

  • Wouldn't normally do what I'm trying to do? Seems pretty common. Why would I want duplicate data of company names under each person rather than storing a ref to just one company model? Am I not doing it right? – Justin Young Jun 04 '15 at 03:13
  • Mongo is NOT a relational database. What you are trying to do is a relational operation. In any case you need to break down the problem recursively. First update your foreign relationship then then master. Take a look at MongooseJS. It puts a relational layer on Mongo. http://mongoosejs.com – Jeffrey A. Gochin Jun 04 '15 at 03:17
  • P.S. I assume you are using a NoSQL DB based on your terminology of "document" and "subdocument". Forgive me if I am misunderstanding. – Jeffrey A. Gochin Jun 04 '15 at 03:18
  • no no you guessed right. I'm using mongoose. I guess what you're saying is save my company and then in the callback update my user then insert the user, right? Not shortcuts? – Justin Young Jun 04 '15 at 03:23
  • Correct. No "easy button here" ;) – Jeffrey A. Gochin Jun 04 '15 at 03:24
  • I know it seems strange, but that is NoSQL. Typically, a documents travel with all of their data in tact. Foreign relations are not part of the concept directly, but are implemented at the application layer, not the DB layer. So duplication of data is the norm. – Jeffrey A. Gochin Jun 04 '15 at 03:29