How to insert ref objectId in nodejs? - javascript

Main Model
{
name: {
type: String,
trim: true,
required: true
},
carModels: [{
type: ObjectId,
ref: 'CarModel'
}]
}
Second Model
{
name: {
type: String,
trim: true,
required: true
},
carModels: [
{
type: ObjectId,
ref: 'CarModel'
}
]
},
Third Model
{
name: {
type: String,
trim: true,
required: true
}
},
Here i am trying to insert the data like this
{
"name": "test",
"phoneNumber": "0123456789",
"email": "m#m.com",
"carMakes": [{
"name": "BMW",
"carModels": [{
"_id": "some id"
}]
}]
}
and it giving me error like
carMakes.0: Cast to [ObjectId] failed for value
here is the create function
export const create = async data => {
const result = await Booking(data).save();
return result;
};
Can anyone tell what I am missing here ..i am learning nodejs

i think the problem is with the _id that you're passing to carModel and since you set the type to ObjectId it has to be in a valid format "either 12 byte binary string, or a 24 hex byte string" and "some id" is not the valid one if you're sending that.
you can check if your id is valid with isValidObjectId() function.
or you can easily generate an ObjectId:
var mongoose = require('mongoose');
var id = new mongoose.Types.ObjectId();

Related

Mongoose text index on array of subdocuments always returns nothing

I have a collection of documents for users to track companies that looks like this:
const mongoose = require("mongoose");
const TrackingListSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "users",
required: true,
index: true
},
email: {
type: String,
required: true,
},
companies: [{
country: {
type: String,
required: true
},
countryCode: {
type: String,
required: true
},
name: {
type: String,
required: true
}
}]
});
TrackingListSchema.index({"companies.name": "text"});
module.exports = mongoose.model("trackinglist", TrackingListSchema);
As you can see, I am creating a text index on the "companies.name" field.
However, when I run a query as such:
TrackingList.aggregate([
{$match: {
"companies.countryCode": "us",
$text: {
$search: "Some Company",
$caseSensitive: false
}
}},
{$project: {
_id: 0,
email: 1,
}}
])
Nothing is returned even though I am sure that at least one tracking list has a company with that name. What am I doing wrong? Am I creating the text index wrong because it is inside an array? I thought I had this working but now I just can't get it to work.

use mongooseModel.find() on schema that has a Schema.Types.Mixed property

I have trouble using postModel.find() query in a schema that defined as Schema.Types.Mixed.
this is a sample of my schema
const PostSchema = new mongoose.Schema({
//.....
address: {
type: String,
required: true,
},
postDetails: {
type: Schema.Types.Mixed,
required: true,
},
author: {
type: Schema.Types.ObjectId,
ref: 'User',
},
//.....
});
this is a sample document stored in db
{
//.....
"state": "Lakes State",
"address": "some address",
"postDetails": {
"type": "Cages",
"condition": "Used"
},
//......
}
it is giving me an empty array if I use this
const queryObject = {
postDetails: {
type: 'Cages',
},
};
return this.postModel.find(queryObject);
but it gives the desired results if I include all the properties like this
const queryObject = {
postDetails: {
type: 'Cages',
condition: 'Used',
},
};
return this.postModel.find(queryObject);
How do i get all matching posts that have postDetails.type = 'Cages' ? without knowing all available properties inside postDetails
there are some similar questions about this here. but most of them are using arrays instead of an object
You can use dot notation for querying embedded documents
postModel.find({
"postDetails.type": "Cages"
});

Push To Mongoose Subdocuments

Hello I am creating a series of groupings describing the roles certain users are taking within the context of helping a client. The object in the Prospect model is called caseworkers. In caseworkers is a series of arrays for the different types of roles done. The equation is to allow the user to push his info as a subdocument called CaseWorker. Basically creating an object with 6 arrays that users can push to. Ive tried a few things and settled on Subdocuments. Any help would be awesome.
Here is my code:
const mongoose = require("mongoose");
const CaseWorker = require("./CaseWorker");
const ProspectSchema = mongoose.Schema({
caseWorkers: {
originators: [CaseWorker.schema],
loanProcessors: [CaseWorker.schema],
documentProcessors: [CaseWorker.schema],
upsells: [CaseWorker.schema],
primaryReso: [CaseWorker.schema],
taxPreparers: [CaseWorker.schema],
secondaryReso: [CaseWorker.schema],
}
module.exports = mongoose.model("prospect", ProspectSchema);
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const CaseWorkerSchema = new Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
role: { type: String },
resoCred1: { type: String },
resoCred2: { type: String },
reminders: [
{
_id: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
userReminded: { type: mongoose.Schema.Types.ObjectId },
reminderDate: { type: Date },
reminderDueDate: { type: Date },
status: { type: String },
daysTilDue: { type: Number },
id: { type: String },
text: { type: String },
clientId: { type: mongoose.Schema.Types.ObjectId, ref: "Prospect" },
},
],
});
module.exports = mongoose.model("caseWorker", CaseWorkerSchema);
router.put("/:_id/caseWorkers/loanProcessors", auth, async (req, res) => {
const prospect = await Prospect.findByIdAndUpdate(req.params._id, {
"$push": {
"loanProcessors": {
"caseWorker": {
"name": req.body.name,
"email": req.body.email,
"role": req.body.role,
"resoCred1": req.body.resoCred1,
"resoCred2": req.body.resoCred2,
},
},
},
});
res.json(prospect);
console.log(prospect);
});
In your approach when updating the document you put caseWorker under loanProcessors but it's declared in the schema the other way around.
To update a nested object you have to use the dot notation to reference the field.
Don't forget to put the object key that represent the field as a string like this "caseWorkers.loanProcessors", because caseWorkers.loanProcessors is an invalid object key in javascript
"$push": {
"caseWorkers.loanProcessors": {
"name": req.body.name,
"email": req.body.email,
"role": req.body.role,
"resoCred1": req.body.resoCred1,
"resoCred2": req.body.resoCred2,
},
},

How to validate Array of Objects in Mongoose

I need to validate the array of objects in my schema
Schema:
user: [{
name: String,
Age: String,
Contact: Number
}]
How to validate name, age and contact.
I assume your user array is inside another schema.
Let's say we have a Course model with users like this:
const mongoose = require("mongoose");
const courseSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
users: [
{
name: { type: String, required: [true, "Name is required"] },
age: { type: Number, required: [true, "Age is required"] },
contact: { type: Number, required: [true, "Contact is required"] }
}
]
});
const Course = mongoose.model("Post", courseSchema);
module.exports = Course;
To validate this in a post route you can use mongoose model validateSync method:
const Course = require("../models/course");
router.post("/course", async (req, res) => {
const { name, users } = req.body;
const course = new Course({ name, users });
const validationErrors = course.validateSync();
if (validationErrors) {
res.status(400).send(validationErrors.message);
} else {
const result = await course.save();
res.send(result);
}
});
When we send a requset body without required fields like age and contact:
(you can also transform validationErrors.errors for more useful error messages.)
{
"name": "course 1",
"users": [{"name": "name 1"}, {"name": "name 2", "age": 22, "contact": 2222}]
}
The result will be like this:
Post validation failed: users.0.contact: Contact is required, users.0.age: Age is required
It will be similar to the usual validation but inside an array, you need to make a validator function as so:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//the custom validation that will get applied to the features attribute.
var notEmpty = function(features){
if(features.length === 0){return false}
else {return true};
}
var CarSchema = new Schema({
name: {
type: String,
required: true,
},
features: [{
type: Schema.ObjectId,
ref: Feature
required: true; //this will prevent a Car model from being saved without a features array.
validate: [notEmpty, 'Please add at least one feature in the features array'] //this adds custom validation through the function check of notEmpty.
}]
});
var FeatureSchema = new Schema({
name: {
type: String,
required: true //this will prevent a Feature model from being saved without a name attribute.
}
});
mongoose.model('Car', CarSchema);
mongoose.model('Feature', FeatureSchema);
By using type key/property:
var breakfastSchema = new Schema({
eggs: {
type: Number,
min: [6, 'Too few eggs'],
max: 12
},
bacon: {
type: Number,
required: [true, 'Why no bacon?']
},
drink: {
type: String,
enum: ['Coffee', 'Tea'],
required: function() {
return this.bacon > 3;
}
}
});

Mongoose populate returns empty array but returns data without populate

I am trying to fetch appointments and populate them with user details and doctor details. I have a schema like this
let appointmentSchema = new Schema({
reason: String,
start: DateType,
end: DateType,
appointmentStamp: Number,
userId: {
type: ObjectId,
ref: 'User'
},
doctorId: {
type: ObjectId,
ref: 'Doctor'
},
approved: Boolean,
held: Boolean,
timeOfAcceptance: Number,
createdOn: { type: Number, default: (new Date().getTime()) },
updatedAt: Mixed
}, {runSettersOnQuery: true})
And on running
Appointment.find({userId: authId}).populate('userId doctorId').exec()
I get an empty array
but
Appointment.find({userId: authId}).exec()
return all the appointments for that user with the userId supplied in find
what am I missing out
Here is a sample appointment
{
"_id": "5a0d424079191657fca9e853",
"reason": "Say Hello",
"approved": false,
"held": false,
"doctor": "5a0add9b577d7916187cd9f2",
"patient": "59f5df20a3071554c5f843e1",
"appointmentStamp": 1510927380000,
"__v": 0,
"createdOn": 1510817910134
}
I tried this and it worked, don't know why
patient: {
type: String,
ref: 'patient'
},
doctor: {
type: String,
ref: 'doctor'
}
instead of ObjectId I used type of String
then the query be like
Appointment.find({patient: authId, canceled: false})
.populate('patient doctor').exec()

Categories

Resources