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"?
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 } })
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.
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.
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.
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
}]
});
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