How use mongoose init model with array of array of object [duplicate] - mongodb

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"?

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

Related

Initial POST to MongoDB creates an empty object within an array I haven't added anything to

Using the MERN stack I am able to add a document (a Property Schema in this case) via Mongoose. The issue is one of the Property Keys (Rooms in this case) is an Array of Objects. When I initially create the Property I don't send any data regarding the Rooms but a blank Object is created, albeit with a MongoDB _id?
I thought Mongoose prevented creating blank Objects / Arrays if no data was sent or am I confusing matters? Why is it happening? And is there a way to prevent this?
Just to be clear when I initially create the Property I'm sending no information and I don't even reference the rooms array in the data sent from axios.
Here is my Schema:
const propertySchema = new Schema({
propertyId: String,
propertyName: String,
rooms: [
rId: String,
type: String,
class: String,
view: String,
price: String
]
})
Arrays implicitly have a default value of [] (empty array).
But you can prevent it by giving a default: undefined option like this:
const propertySchema = new Schema({
propertyId: String,
propertyName: String,
rooms: {
type: [
new Schema({
rId: String,
type: String,
class: String,
view: String,
price: String,
}),
],
default: undefined,
},
});
Docs (in the Arrays section)
What I realised was I had two controllers, postPropertyController and patchPropertyController. As described in the question when I post the property for the first time I don't include anything in the req.body about the rooms. However, in the postPropertyController I was still doing this...
const propertySchema = new Schema({
propertyId: String,
propertyName: String,
rooms: [
rId: String,
type: String,
class: String,
view: String,
price: String
]
})
What I needed to do to clear the empty object in the rooms array was this...
const propertySchema = new Schema({
propertyId: String,
propertyName: String,
rooms: []
})
Later in the application flow I used a patch method and the patchPropertyController to update the rooms array.
Shout out to #suleymanSah for suggesting something that made me take another look at the code side by side.

Mongoose mixed SchemaType

I couldn't understand that for what purpose mongoose schemaType is used for. If someone could explain it will be helpful.
I'm have to reference another schema from a schema i want to know if we can get the details of all schema together when we do a findOne() on mongoose.
mixed schema means whatever you want the type to be. if you input a String, Number, Date, mongoose will let you do that. However according to documentation, mongoose ref does not work with mixed.
Note: ObjectId, Number, String, and Buffer are valid for use as refs.
if you use mixed, and ref it, you won't be able to query it back.
If you start all over(delete the database and reinsert again), use ObjectId instead of Mixed.
var storySchema = Schema({
author : { type: ObjectId, ref: 'Person' },
});
If you wish to retain old database, the best way is to change mixed to string
var storySchema = Schema({
author : { type: String, ref: 'Person' },
});

How to dynamically populate mongoose document reference at runtime?

I have a schema that has a field that could reference different schema.
var HistorySchema = new Schema({
type: {type: String, required: true},
objectId: {
type: Schema.Types.ObjectId,
required: true,
},
changed: {type: Schema.Types.Mixed}
})
The documents of this schema allows me to keep track of changes happens in different types of objects with objectId.
For example, if User has changed name from 'John' to 'Steve', a History document would have:
{
type: 'User',
objectId: '55fa6bf0831ba3fa0879e7e8',
changed: {name: {oldValue: 'John', newValue: 'Steve'}}
}
Obviously, type can be many different things.
My question is, can I magically populate the objectId field without knowing type before the query?
I know I can do:
History.query({...}).populate('objectId', null, 'User').exec(...);
But that requires me to know the type is User when the query is constructed.
And obviously I can do a second query manually given the type and objectId.
For example, is it possible to save the ref type of a document (not schema) at runtime and take advantage of that? I look around and don't seem to find a way.

Mongoose variable schema reference

I'm looking for the best way to have a parent model that references variable child models. Is there a way to set the reference upon saving the parent model, then have it populate the child automatically? If not, what is the best way of achieving a parent model that has variable sub-fields.
var ChildSchema1 = new Schema({
field1: String,
field2: String
});
var ChildSchema2 = new Schema ({
field3: Number,
field4: String
});
var ParentSchema = new Schema({
name: {type: String, required: true},
child_ref: {type: ObjectId, ref: ChildSchema1 OR ChildSchema2}
});
I had a similar problem, where I needed to do schema inheritance. It seems like this github project will work for us both:
https://github.com/briankircho/mongoose-schema-extend

Mongoose OR operator for schema definitions

Does Mongoose support, or is there an available package that supports multiple "options" for the embedded schemas in an array?
For example, the things property can contain only one of two schemas:
new Schema({
things: [{
requiredProp: String,
otherProp: Number
}, {
otherOption: Number
}]
});
In other words, I do not want to just allow anything (AKA Schema.Types.Mixed) to be stored in this property, but only these two possible definitions.
Or, do schema design recommendations exist to avoid this problem?
You should only define one dict in the array type of the schema, and then set if they are required or not with the mongoose schema types logic. Use pre save if you want to do more logic to assure that either one of the fields have been set, like this:
var MySchema = new Schema({
things: [{
requiredProp: {type: String, required: true},
otherProp: Number,
otherOption: Number,
}]
});
MySchema.pre('save', function(next) {
if (!this.otherProp && !this.otherOption) {
next(new Error('Both otherProp and otherOption can\'t be null'))
} else {
next()
}
})
Opon saving the object it will return an error if neither otherProp nor otherOption has been set.