I'm using mongoose and trying to get document by specific value of field on it and subdocument field's specific value. I dig a lot but I was unable to find anything matching - I am also new to MongoDb.
So my schema looks like :
messageSchema = Schema candidateId: {type: string},
template: {type: Schema.Types.ObjectId, ref: 'MessageTemplate'},
messageTemplate = Schema name:{type: string}, isActive:{type: boolean}
So I want to get all messages that have certain candidateId and messageTemplate.isActive equal to true.
I couldn't figure out query so I am doing work around like this
Message.find({candidateId: candidateId})
.populate('template')
.then(res => res.fileter(message => message.template.isActive)
It's working but I'm guessing it's possible to create better query, any help will be great.
Related
var publisherSchema = Schema({
_id : Number,
name : String,
founded : Number,
books : [{ type: Schema.Types.ObjectId, ref: 'Book' }]
});
var bookSchema = Schema({
_id : Number,
title : String,
author : [{type: String}],
pages: Number,
language: String
});
var Book = mongoose.model('Book', bookSchema);
var Publisher = mongoose.model('Publisher', publisherSchema);
Trying to understand ObjectId: the type for books as listed as Schema.Types.ObjectId. Objectids are generated by Mongodb automatically.
If I add ids to the book array manually, type will be just strings. Do I need to somehow also generate Objectids saved in the books array so when I make a query (findById) I will find it or is it enough if I just add those id's as strings?
I read in another post its better to generate ObjectIds and not just strings to reduce space. Im confused by this as I read that they normally generated by mongodb. If I can (and should) generate them for ids -how to?
When I make a reference
books : [{ type: Schema.Types.ObjectId, ref: 'Book' }]
that is just for the developer to know that the id's are suppose to belong to the books collection, there is no internal linking functionality to the books collection from the publisher collection?!
Thanks!!
I have a schema like this
const Schema1 = new Schema({
field11: String,
field12: [
{ _id: Schema.Types.ObjectId,
title: String
}
]
})
and another schema which has a field to reference to filed of the first collection as below
const Schema2 = new Schema({
field21: String,
field22: [
{_id: {type: Schema.Types.ObjectId},
{ref: 'Schema1.filed12'}
]
})
I need to populate field22 in schema2. How do I need to do it.
The below query doesn't work for me.
Schema2.find(field21).populate('Schema1.field12')
According to the documentation:
The ref option is what tells Mongoose which model to use during population, in our case the Story model. All _ids we store here must be document _ids from the Story model.
You are attempting to store non-id fields as a reference that should point to subdocuments that are nested in an array of your Schema1 model. This simply doesn't work.
I'm creating a mern app, and pretty new to mongodb and mongoose, and I'm currently struggling with the concept of the subdocument in mongodb and how to perform crud operations in express. I've been researching and haven't found many tutorials or articles on subdocuments, mostly the referenced documents and population.
I have two separate schemas
var ProjectSchema= new mongoose.Schema({
title:{
type:String,
required:true,
unique:true
},
description:String,
lists: [ListSchema]
})
var ListSchema= new mongoose.Schema({
name: {
type:String,
required:true
}
})
Currently, i'm trying to insert data into the List schema.
listRouter.post('/api/project/:projectId/list/new', asyncMiddleware(async function(req,res,next){
Project.findById(req.params.projectId, await function(err,items){
items.lists.push(req.body)
items.save();
res.json(items)
})
}))
What happens is that the data are inserted into the Project.lists but when I check the List collection in mongodb, it's empty.
From my reading the sub documents documentation , it stats you can't save the sub documents individually, you have to do via the parent document- which I have in the code above.
Doesn't the List collection supposed to automatically get the new data after saving the Project document? Or something else is happening? Any input would be appreciated.
We're using collection2 (obviously with simple schema) and trying to save an array of objects to a single property on the Meteor.users collection. For example our data might be:
[
{name: "paul"},
{name: "darryn"},
{name: "tom"}
]
in reality our object is more complex
when trying to do this with $set in an update on the users collection we've either gotten 500's or managed to delete the user object entirely when turning off validation.
we've also gotten the following error a number of times:
Validation object must have at least one operator / meteor mongo
This StackOverflow Question mentions it but doesn't offer a solution that makes sense in our context.
My question is two fold. How should the schema be defined for this as we've been trying with type: [Object] which I'm not sure is right, and secondly how should the update statement be created in the method.
Any thoughts, or help would be amazing.
First define the schema for your complex object. Here I've just added age as a key:
Schema.Foo = new SimpleSchema({
name: { type: String },
age: { type: Number, min: 0 }
});
Then augment the user schema with a key whose type is an array of the type you just defined
Schema.User = new SimpleSchema({
foo: { type: [Schema.foo] },
etc...
});
I have the following 2 schemas:
Company Event:
var companyEventSchema = new Schema({
name : String,
description
date : Date,
attendees : [ { type : Schema.ObjectId, ref : 'Member' } ],
]});
And Member
var memberSchema = new Schema({
name : String,
emailAddress: String,
password :String,
created: { type: Date, default: Date.now }
});
Is the way i've ref'd Member from companyEventSchema correct?
I'm trying to do something a long the lines of a dbref.
I saw theres a separate project for that though... mongoose-dbref
However, the mongoose docs say the above provides "dbref like functionality"
Which would be more efficient?
You only need to use an actual DBRef (and mongoose-dbref) for the case where a field can contain ObjectIds that reference documents in potentially more than one collection. A DBRef is a tuple of an ObjectId, a collection name, and an optional database name.
Mongoose ref: fields, however, contain just an ObjectId and it's the Mongoose schema that defines what one collection the ObjectIds reference.
So Mongoose ref: fields are more efficient and should always be used unless you need the multi-collection reference support that DBRef provides.