MongoDB using mongoose for populate - mongodb

I am having collection1 with one of the column as ref of collection2. Now i want to populate(join) collection1 and collection2 with some condition on collection2 fields. Is it possible?
What i want to do is
models.Encounter
.where('practice').equals(practice)
.populate({
path:'chart',
match:{firstName:{ $regex: new RegExp(Name.toLowerCase(), 'i') }},
select:'firstName lastName'})
.populate('provider', 'firstName lastName')
.populate('signedBy', 'firstName lastName')
.sort('-date')
.limit(100)
.exec(function (err, encounters) {})
Here charts is collection and for me match is not working..Where Name comes from jade engine. null values are coming for firstname
Practice Schema:
The schemas are
var practiceSchema = mongoose.Schema({
name: String,
internalName: String,
address: addressSchema,
phone: String,
taxId: String
});
Chart Schema:
var chartSchema = mongoose.Schema({
created: Date,
updated: Date,
practice: {type: mongoose.Schema.ObjectId, ref : 'practices', required: true},
mrn: String,
firstName: String,
lastName: String,
emailWork: String,
phoneHome: String,
phoneMobile: String,
dob: Date,
married: Boolean,
smoker: Boolean
});
Now i want to get data from Encounters by populating charts and also charts.firstName == 'XYZ' and charts.lastName == 'ABC'.. I have done this by getting all data from encounters and then applying filter on charts. But it is taking too much of time..

Related

Get documents with specific value in an array inside the document in mongodb

my document is as below
const mailSchema = new Schema ({
from: String,
to: [{
emailId: String,
status: Number
}],
cc: [{
emailId: String,
status: Number
}],
bcc: [{
emailId: String,
status: Number
}],
subject: String,
content: String,
status: Number,
createdBy: Schema.Types.ObjectId
}
How to retrieve document where 'to.emailid' contains a given value?
I have used below code but it is not working.
const emailtext = 'test#gmail.com'
MailSchema.find({'to.emailId': emailtext });
I think your schema is incorrect. what you want to do is to have a document that contain an object file. But what you did is a document with an array of file objects. so i think you should remove all the square bracket in the schema, then it should look like this.
//Mail Schema without array of objects.
const mailSchema = new Schema ({
from: String,
to: {
emailId: String,
status: Number
},
cc: {
emailId: String,
status: Number
},
bcc: {
emailId: String,
status: Number
},
subject: String,
content: String,
status: Number,
createdBy: Schema.Types.ObjectId
}
However if what you really want is an array of objects, then your query should also include the index of the array you want to get the emailId from.
Example.
MailSchema.find({'to[0].emailId': emailtext });

Mongodb Schema using mongoose

This is my user schema :
const userSchema = new Schema({
email: String,
username: String,
password: String,
secretToken: String,
active: Boolean,
type: String
}, {
timestamps: { // this will give us the detail when the account is created
createdAt: 'createdAt',
updatedAt: 'updatedAt'
}
});
this is my requirement Schema:
const requirementSchema = new Schema({
name: String,
age: String,
class: String,
subject: String,
email: String
}, {
timestamps: { // this will give us the detail when the requiremnt is created
createdAt: 'createdAt',
updatedAt: 'updatedAt'
}
});
how can I bring id from user schema to the requirement schema as secondary key?
I think mongodb is not meant for relationship. I could led to very bad practice if your database grow. But you can try https://docs.mongodb.com/manual/reference/database-references/#DatabaseReferences-DBRef for Database References.
There is no primary key foreign key concept in Mongodb. and normalization is also discouraged in mongodb.

Mongoose: does a custom _id need to be declared as an index and be unique

Here is the common way to define a collection structure with Mongoose :
var UserSchema = new Schema({
_id: Schema.Types.ObjectId,
username: String,
...
});
And Now I want _id field declared as Number type :
var UserSchema = new Schema({
_id: Number,
username: String,
...
});
The problem is, do I need to declare more infomation about _id ? Such as :
var UserSchema = new Schema({
_id: {type: Number, required: true, index: {unique: true}},
username: String,
...
});
I am not sure whether MongoDB would do it automatically.
if you know the answer, could you leave a comment below ? Thank you!
Well, after some practice, I realized that, MongoDB would set _id as PRIMARY KEY (NOT NULL + UNIQUE INDEX) automatically. So, just type:
_id: Number,
...

MongoDB $pull value from array of ObjectIDs

I have this document in my collection:
{
"_id" : ObjectId("52718433e18a711923000005"),
"owners" : [
ObjectId("52718433e18a711923000004"),
ObjectId("52ed40dccc5bc50000000003"),
ObjectId("52ed4171abe2780000000003")
]
}
I have the following statement, where I am trying to remove one of the values in owners field:
Business.update({_id:req.body._id}, {$pull:{"owners":req.body.userid}}, function(err){
if(err){
res.json(500, {message:"Could not remove user from admin list"});
}else{
res.json(200);
}
});
I know that req.body._id and req.body.userid have valid values:
{ _id: '52718433e18a711923000005',
userid: '52ed4171abe2780000000003' }
Other operations, such as finding business by ID, etc, work, so it's not an ObjectId format issue. What else could it be?
--
Edit: here is my (abbreviated) schema definition:
var BusinessSchema = new Schema({
business_name: {type: String, required: true},
owners: {type: Array}
});
Your current schema doesn't provide any direction to Mongoose regarding the data type contained within the owners array field. If you want Mongoose to cast your string to an ObjectID you need to provide type information in your schema:
var BusinessSchema = new Schema({
business_name: {type: String, required: true},
owners: [{type: Schema.ObjectId}]
});
It looks like a conversion to ObjectId is required when trying to match values to pull. But not to search. So this works:
var ObjectId = require('mongoose').Types.ObjectId;
Business.update({_id:req.body._id}, {$pull:{"owners": new ObjectId(req.body.userid)}}, function(err){
if(err){
res.json(500, {message:"Could not remove user from admin list"});
}else{
res.json(200);
}
});
--
Edit: So, if I change my schema from owners: {type: Array} to owners: [Schema.Types.ObjectId], I can skip the conversion, and my original statement works.

Mongoose schema change (with _id change)

I have a schema named card to update
from {_id: ObjectId, id: String, ....}
to {_id: String(same as id), id: String, ....}
and update also a schema named users which is like
{name: String, email: string, cards: {type: ObjectId, ref: 'card'}}
how can i do this ?