Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define a key named "type" in Mongoose?

I have a Schema definition with a nested object that looks like this:

mongoose.Schema({
    name: String,
    messages: [{
        type: String,
        message: String
    }]
});

Mongoose doesn't interpret this as I would like because there is a key named type, which conflicts with Mongoose's syntax for defining defaults, etc. Is there a way to define a key named "type"?

like image 221
Dmitry Minkovsky Avatar asked Mar 15 '14 15:03

Dmitry Minkovsky


People also ask

What is the primary key of a MongoDB schema?

In MongoDB, there is no primary key. All you need is an unique: true index and you’re good to go. const DocumentSchema = new Schema ( { _id: false, documentId: { type: String, unique: true, required: true } })

What is the use of $type in MongoDB?

New in MongoDB 4.4 $type (Aggregation) - returns the BSON type of the argument. $type returns documents where the BSON type of the field matches the BSON type passed to $type. For documents where field is an array, $type returns documents in which at least one array element matches a type passed to $type.

Is _ID field required for Mongoose to work?

I have found out that all documents must have a _id key for mongoose to work. mongoose will error if there is no such key. I have now simply declared the _id field as a String. Show activity on this post.

What is a unique index in MongoDB?

A unique index ensures that the indexed fields do not store duplicate values; i.e. enforces uniqueness for the indexed fields. By default, MongoDB creates a unique index on the _id field during the creation of a collection.


1 Answers

Oh, I remember this annoying problem, it took me ages to find out that the problem is that type is read by mongoose schema.

Just specify a type:String inside the type label

mongoose.Schema({
  name: String,
  messages: [{
    type: {type: String},
    message: String
  }]
});
like image 109
ekeren Avatar answered Oct 23 '22 19:10

ekeren