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
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.
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.
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.
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.
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'
}
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With