If I have a parent schema like:
{
doc_name:String,
doc_collection:[?????]
}
and subdoc children:
child1 =
{
child_type: String,
property1: String,
property2: Number
}
child2 =
{
child_type: string,
different_property1: Number,
much_different_property2: String
}
can parentschema.doc_collection hold subdocuments of both child1 and child2 schemas?
Or do I have to do:
{
doc_name:String,
doc_collection:
{
child1:[child1],
child2:[child2]
}
}
I would normally create a subdocument schema that can encompass properties of ALL the types of objects I'm tring to stick in the array, but these are just too different. From the controller perspective, the child schemas are all of type doc_collection.
if my memories are good, mongoose doesn't handle complex type array (in term of content validation)
that means, if your model is like :
{
doc_collection : []
}
{
doc_collection : [child1]
}
is the same.
and the worst is that if your model is
{
doc_collection : [child1]
}
you would be able to add anythind in doc_collection array
myModel.doc_collection.push(anyChild2);
take a look to the array chapter : http://mongoosejs.com/docs/schematypes.html
Related
I am trying to find some documents given an array of objects and inside each object, there is an id "courseId" which will be used to find the required documents from the schema with the same id.
Here is the array of objects:
courseIds = [
{"courseId":"638c139b147e2173163fd976",
"_id":"63906c07b9b09cd81e48480d"
},
{"courseId":"638c131a147e2173163fd96b",
"_id":"63908c9f1897b57aa6ece69f"
}]
and if the schema contains the following objects:
const courseSchema =
[{
"_id":"638c131a147e2173163fd96b",
"courseTitle":"Neural Networks",
"price":"5000",
"shortSummary":"Its a lovely course about NNs, Sequence Models.",
"subject":"Deep Learning"
},
{
"_id":"638c139b147e2173163fd976",
"courseTitle":"Graphics",
"price":"3000",
"shortSummary":"Its a lovely course about Projection, 2D & 3D Transformations.",
"subject":"Computer Graphics"
},
{
"_id":"638c131a147e9053163fd281",
"courseTitle":"Operating Systems",
"price":"4500",
"shortSummary":"Its a lovely course about Scheduling, learning about drivers and peripherals.",
"subject":"Hardware"
}]
What I want to do is I want to find/return only the courses from the courseSchema whose ids are present in the courseIds array, like here it would only return two courses:
{
"_id":"638c131a147e2173163fd96b",
"courseTitle":"Neural Networks",
"price":"5000",
"shortSummary":"Its a lovely course about NNs, Sequence Models.",
"subject":"Deep Learning"
},
{
"_id":"638c139b147e2173163fd976",
"courseTitle":"Graphics",
"price":"3000",
"shortSummary":"Its a lovely course about Projection, 2D & 3D Transformations.",
"subject":"Computer Graphics"
}
since their ids "_id" are present in the courseIds array ("courseId == _id").
I tried to do the following:
const docs = courseSchema.find().where('_id').in(courseIds);
and
const docs = courseSchema.find({ '_id': { $in: courseIds} });
and it always return an empty array (no matches).
Why doesn't it work?
courseIds id a array object, in order to match _id with $in the array must be of only _id like ["638c139b147e2173163fd976","638c131a147e2173163fd96b"].
for that you can make another array from courseIds array object and use that as in query with $in.
courseIds = [
{
"courseId":"638c139b147e2173163fd976",
"_id":"63906c07b9b09cd81e48480d"
},
{
"courseId":"638c131a147e2173163fd96b",
"_id":"63908c9f1897b57aa6ece69f"
}
] //Your courseIds array object
let onlyIds=[] // declaring array to store only _ids
for(let i=0;i<courseIds.length;i++){
if(!onlyIds.includes(courseIds[i].courseId)) //checking id exist in array, if not exist push _id to onlyIds aarray
onlyIds.push(courseIds[i].courseId); //push _id
}
console.log(courseId)//output=>["638c139b147e2173163fd976","638c131a147e2173163fd96b"]
const docs = courseSchema.find({ _id: { $in: onlyIds } }); //final query
My document schema is as follows:
const CollectionSchema = mongoose.Schema({
ImageCategory:{type:String,required:true},
imgDetails: [
{
_id: false,
imageUrl:{type:String},
imageName:{type:String},
imageMimeType:{type:String},
}
],
Date: {
type: String,
default: `${year}-${month}-${day}`,
},
},{timestamps: true,})
So in the database for example one document has multiple images with a single image category. What I am trying to do is I want to delete an object from imgDetails array.
Let me explain my question more precisely: imgDetails is an array
Explanation: I want to loop in imgDetails and then find (where imgageUrl === req.body.imageUrl) if its match delete that whole object which have that req.body.imageUrl and then update the document.
Please guide me on how to write such a query. Regards
Demo - https://mongoplayground.net/p/qpl7lXbKAZE
Use $pull
The $pull operator removes from an existing array all instances of a value or values that match a specified condition.
db.collection.update(
{},
{ $pull: { "imgDetails": { imageUrl: "xyz" } } }
)
I'm trying to wrap my head around the Mongoose Populate syntax and structure. I have two schemas. The Parent has an array of Child references.
const Parent = new Schema({
name: String,
children: [{type: Schema.ObjectId, ref: 'Child'}]
});
const Child = new Schema({
name: String
});
To populate the Parent I've been doing this:
Parent
.findById(parent.id)
.populate('children')
.exec( (err, parent) => {
parent.children = arrayOfInsertedChildDocs;
parent.save();
});
The Parent references save, but is there a way to query for Parents that have a reference to a certain Child? For example all Parents that have a reference to a child with the Id of ObjectId('xxxxxxxxx') in their children array?
This is what I've been trying but it's not working.
let query = { "children._id": mongoose.Types.ObjectId(childId) };
Parent.find(query, (err, parents) => {
//process parents
})
Is this possible?
Figured it out. The query to get the Parent from a child id in the nested array is:
Parent
.find({"children":ObjectId(child.id)})
.populate("children")
.exec((err,parents) => {
//process parents
});
You want to search for element in MongoDB array set. Suppose you have a document.
{
name :"harry",
childen:["10ahhdj20","9ajskjakj9","8aiisu38","2jjaksjah0"]
}
So for searching inside an array list, you can use this.
db.parents.find( { tags: { $all: [ "10ahhdj20", "812922dd" ] } } )
You will get all the parents who have these children.
Hi I am facing a problem in updating an embedded object array using mongoose!
Here is the Schema:
var event = {
eTime : [String]
};
var schedule = {
events: [event]
};
var group = {
gName: {type:String},
sDate: { type: Date, default: Date.now },
schedules: [schedule]
};
MainSchema {
id : String,
groups : [group]
};
The thing which I want to do is that to update the array of eTime in events with an object of schedules. I am using this query
db.demoDb.update({
'id': 'MongoDb',
'groups':{
$elemMatch:{
'gName':'noSql'
}
}
},
{
$push:{
'groups':{
'schedules':{
'events':{
'eTime':'01-Marach-15'
}
}
}
}
}
)
but the schedules->events->eventTime is not updating with a value!!!
What wrong I am doing here?
My Main Scenario is to find the id(MongoDB) with associated gName and then update its schedules array of it.
My find query is working great but can not update the schedules... and events can be many
If I'm reading your schema correctly, the core part is an array containing an array containing an array containing an array of strings. I think you would do much better "inverting" the schema so each document represents an event. Metadata grouping multiple events can be duplicated into each event document. An example:
{
"event" : "cookie bake-off",
"gName" : "baking",
"sDate" : ISODate("2015-03-02T21:46:11.842Z")
}
The update that you are struggling with translates into an insertion of a new event document in the collection.
Given the schema:
{
_id: ObjectID,
city:
{ units:
{ abc: {},
def: { tuid : String },
...
xxx: { tuid : String }
}
}
I would like to return, for a particular _id, all the properties of units who's subproperty tuid is, for example, 123.
I have searched for information about this but array operations keep popping up instead of what I need.
Thank you.