Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb type reference node

I am trying reference another object in a model in node,

User = new Schema({
        username: {
            type: String,
            index: {unique: true}
        }
});

Idea = new Schema({
        Creator: {
            type: User
        }
});

but I get this error Undefined type at "creator" Did you try nesting Schemas? You can only nest using refs or arrays. I believe I want to use refs, but could not find documentation on it, can some one help me out. Thanks

like image 390
Doboy Avatar asked Feb 18 '12 05:02

Doboy


People also ask

How do I reference in MongoDB?

MongoDB applications use one of two methods to relate documents: Manual references save the _id field of one document in another document as a reference. Your application runs a second query to return the related data. These references are simple and sufficient for most use cases.

What is type in MongoDB?

Introduction to the MongoDB $type operator The $type is an element query operator that allows you to select documents where the value of a field is an instance of a specified BSON type.

What is ref in Mongoose schema?

The ref option is what tells Mongoose which model to use during population, in our case the Story model. All _id s we store here must be document _id s from the Story model. Note: ObjectId , Number , String , and Buffer are valid for use as refs.

What is Dbref in MongoDB?

DBRefs are similar to manual references in the sense that they also contain the referenced document's _id. However, they contain the referenced document's collection in the $ref field and optionally its database as well in the $db field.


2 Answers

I found out the answer to my own question here it is.

User = new Schema({
    username: {
        type: String,
        index: {unique: true}
    }
});

Idea = new Schema({
    Creator: {
        type: Schema.ObjectId,
        ref: 'User'
    }
});
like image 176
Doboy Avatar answered Sep 27 '22 23:09

Doboy


I'd like to add a reply to this question because it's the first result in Google.

No you can't use Nested Schema as the other replies say. But you can still use the same object in different schema.

// Regular JS Object (Not a schema)
var Address = {
    address1: String,
    address2: String,
    city: String,
    postalcode: String
};

var Customer = new Schema({
    firstname: String,
    lastname: String,
    address: Address
});

var Store = new Schema({
    name: String,
    address: Address
});

That way you can modify the Address Object to make the changes available on all your schemas sharing the object.

like image 32
doobdargent Avatar answered Sep 27 '22 22:09

doobdargent