Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Mongoose only support embedded documents in arrays?

I have some data in MongoDB that looks like this:

{
    name: "Steve",
    location: {
        city: "Nowhere, IL",
        country: "The United States of Awesome"
    }
}

I’m using objects to organize common data structures (like locations), which in Mongoose might map nicely to Schemas. Unfortunately, they don't appear to really work in Mongoose.

If I just embed an object, like this:

{
    name: String,
    location: {
        city: String,
        country: String
    }
}

It appears to work, but exhibits some bizarre behavior that causes problems for me (e.g. instance.location.location returns location, and subobjects inherit methods from the parent schema). I started a thread on the Mongoose list, but it hasn’t seen any action.

If I embed a Schema, like this:

{
    name: String,
    location: new Schema({
        city: String,
        country: String
    })
}

…my application doesn’t start (Schema isn’t a type supported by Mongoose). Ditto for

{
    name: String,
    location: Object
}

…which wouldn’t be ideal, anyway.

Am I missing something or do my schemas not jive with Mongoose?

like image 328
s4y Avatar asked May 30 '11 02:05

s4y


2 Answers

I did something similar:

var Topic = new Schema({
      author    : ObjectId
    , title     : String
    , body      : String
    , topics    : [Topic]
});

This worked fine in my tests. However, removing the array brakets resulted in an error. Looks like a bug to me.

https://github.com/LearnBoost/mongoose/blob/master/lib/mongoose/schema.js#L185

Dumping types, I only get String, Number, Boolean, DocumentArray, Array, Date, ObjectId, Mixed -- which appears to be on purpose, schema/index.js doesn't look like it dynamically registers new Schemas to the list of types, so I am guessing this isn't a supported use case, yet.

https://github.com/LearnBoost/mongoose/issues/188

"Embedding single docs is out of the question. It's not a good idea (just use regular nested objects)"

Josh

like image 106
Josh Avatar answered Oct 28 '22 22:10

Josh


It looks like this was a bug, it’s been fixed in Mongoose 2.0!

like image 20
s4y Avatar answered Oct 28 '22 22:10

s4y