How do I pass an object element in express using Mongo? - node.js

I want to pass a whole object from an ejs template
For example:
var schema = ... {
Name: [{
}]
}

With this you can achieve it, hope that's what you ask...
notifications: {
notifiId: {type: Schema.Types.ObjectId, ref: 'Notifications' },
viewed: { type: Number, default: 0 }
},
and to find it:
model_Variable.findById(req.params.id).populate("notifiId").exec(function (err,
callBack) {});
Source: How to populate in this case Mongoose

Related

Using DELETE Rest api to remove array object from Mongodb

I am using Node.js, express, mongodb, and mongoose. I have two files: favorite and favorite-route.
"favorites" in the schema has multiple objects in it array. Given the mongodb assigned _id, I would like to create a delete method to gremove the specified object in the array.
Here is my schema in favorite:
userID:{
//type: String,
type: mongoose.Schema.Types.ObjectId,
ref: "user",
required: true,
unique: true
},
favorites:[{
publication: {
type:mongoose.Schema.Types.ObjectId,
ref: "Pet"
},
id: {
type: String,
required: true
},
comment: {
type: String,
required: true
}
}]
})
favoritesSchema.statics.deleteFavorite = async (favID)=>{
return await Favorite.findOneAndUpdate({favID})
}
This is my delete method in favorite-route file:
router.delete('/:favID', async (req,res)=>{
let doc = await Favorite.deleteFavorite(req.params.favID)
if(doc){
doc.splice(req.params.favID);
res.send(doc)
return;
}
res.status(404).send({error: "no se encontró esa publicación"})
})
And lastly, here is my http:
DELETE {{host}}/api/favorites/626eddd14762eb4ae4c77f9e
When i test this, it gives me the error:
TypeError: doc.splice is not a function
I'd appreciate any tips and insight. I have spent a while searching for answers but most suggested using $pull, which I am unsure how to implement in the delete method.
Thank you :)
you should do.
Favorite.updateOne(
{ userID: user._id }, // this is the query to find the desired favourite list
{ $pull: { favorites: { id : req.params.favID }} }, // this removes
);

Nested document referencing in mongodb with mongoose

I am trying to build a kanban as a project for my portfolio with the mern stack with a rest api. I am having issues querying the models with deeply nested objects in it. My idea is to have the lists be referenced in the project, the task be referenced in the list and the user be referenced in the task and the project as a contributor. My issue is getting the information of the task (title, etc.) through populating the project model with mongoose, or MongoDB for that matter. How should I approach this? Is it even possible to do with MongoDB? I see a lot of people doing this with a sql database. The four model schemas are as follows:
const projectSchema = new Schema({
title: { type: String, required: true, max: 32, trim: true },
lists: [{ type: Schema.Types.ObjectId, ref: 'List' }],
contributors: [{ type: Schema.Types.ObjectId, ref: 'User' }],
});
const listSchema = new Schema({
title: { type: String, required: true, max: 32, trim: true },
tasks: [{ type: Schema.Types.ObjectId, ref: 'Task' }],
});
const taskSchema = new Schema({
title: { type: String, required: true, max: 38, trim: true },
text: { type: String, max: 255, trim: true },
assignee: { type: Schema.Types.ObjectId, ref: 'User' },
});
const userSchema = new Schema(
Name: { type: String, required: true, trim: true },
projects: [{ type: Schema.Types.ObjectId, ref: 'Project' }],
tasks: [{ type: Schema.Types.ObjectId, ref: 'Task' }],
);
The issue I have is displaying the tasks in the list. When I populate the list with the project call, I get the ObjectId of the task, but would like to get the task title, which as it seems is not possible by applying the .populate call again. I have the following api controller/route:
router.get('/:projectId', async (req, res) => {
try {
const project = await Project.findOne({
_id: req.params.projectId,
}).populate('lists', 'title tasks');
res.json(project);
} catch (error) {
if (error) {
console.error(error.message);
res.status(500).send('Server Error');
}
}
});
How would I approach getting the task title and later on the user name for all the tasks in the list referencing a project?
So I found a solution to this. Not sure if this is the most efficient method to solve this. If anyone can provide a better solution, please post it on here.
I found the mongoose documents explains quite well how to populate over multiple levels.
https://mongoosejs.com/docs/populate.html#deep-populate
Now the solution for the answer looks as follows
router.get('/:projectId', async (req, res) => {
try {
const project = await Project.findOne({
_id: req.params.projectId,
}).populate({ path: 'lists', populate: { path: 'tasks' } });
res.json(project);
} catch (error) {
if (error) {
console.error(error.message);
res.status(500).send('Server Error');
}
}
});

How to find a record based on id in an array in mongoose

I am trying to fetch record based on the id present in an array but unfortunately the query fails.I have a record as follows
My Schema,
var EmployeehierarchySchema = new Schema({
created_by: {
type: Schema.ObjectId,
ref: 'Employee'
},
parents: {
type: Array,
default: ''
},
childrens: {
type: Array,
default: ''
},
});
"parents" : [
ObjectId("586e3bc35f01e338d7341304")
]
and i want fetch this record based on id and i wrote the following code
var item = {'parents':req.id};
Employeehierarchy.find(item).exec(function (err, employeehierarchy) {});
But i am getting empty eve i have the records.Can anyone suggest help.Yhanks.
Try this:
Employeehierarchy.find({'parents':{$in:[req.id]}).exec(function (err, employeehierarchy) {});

Mongoose Populate - array

can someone please help me with population of this schema? I need to populate array of Staff by their userId.
var PlaceSchema = new Schema ({
name: { type: String, required: true, trim: true },
permalink: { type: String },
country: { type: String, required: true },
...long story :D...
staff: [staffSchema],
admins: [adminSchema],
masterPlace:{ type: Boolean },
images: []
});
var staffSchema = new Schema ({
userId: { type: Schema.Types.ObjectId, ref: 'Account' },
role: { type: Number }
});
var adminSchema = new Schema ({
userId: { type: Schema.Types.ObjectId, ref: 'Account'}
})
var Places = mongoose.model('Places', PlaceSchema);
I tried to use this query, but without success.
Places.findOne({'_id' : placeId}).populate('staff.userId').exec(function(err, doc){
console.log(doc);
});
Polpulation is intended as a method for "pulling in" information from the related models in the collection. So rather than specifying a related field "directly", instead reference the related fields so the document appears to have all of those sub-documents embedded in the response:
Places.findOne({'_id' : placeId}).populate('staff','_id')
.exec(function(err, doc){
console.log(doc);
});
The second argument just returns the field that you want. So it "filters" the response.
There is more information on populate in the documentation.

Mongoose Relationship Populate Doesn't Return results

var SecuritySchema = new Mongoose.Schema({
_bids: [{
type: Mongoose.Schema.Types.ObjectId,
ref: 'BuyOrder'
}],
_asks: [{
type: Mongoose.Schema.Types.ObjectId,
ref: 'SellOrder'
}]
});
var OrdersSchema = new Mongoose.Schema({
_security: {
type: Mongoose.Schema.Types.ObjectId,
ref: 'Security'
},
price: {
type: Number,
required: true
},
quantity: {
type: Number,
required: true
}
});
// declare seat covers here too
var models = {
Security: Mongoose.model('Security', SecuritySchema),
BuyOrder: Mongoose.model('BuyOrder', OrdersSchema),
SellOrder: Mongoose.model('SellOrder', OrdersSchema)
};
return models;
And than when I save a new BuyOrder for example:
// I put the 'id' of the security: order.__security = security._id on the client-side
var order = new models.BuyOrder(req.body.order);
order.save(function(err) {
if (err) return console.log(err);
});
And attempt to re-retrieve the associated security:
models.Security.findById(req.params.id).populate({
path: '_bids'
}).exec(function(err, security) {
// the '_bids' array is empty.
});
I think this is some sort of naming issue, but I'm not sure, I've seen examples here and on the moongoose website that use Number as the Id type: http://mongoosejs.com/docs/populate.html
The ref field should use the singular model name
Also, just do:
models.Security.findById(req.params.id).populate('_bids').exec(...
My main suspicion given your snippet at the moment is your req.body.order has _security as a string instead of an array containing a string.
Also, you don't need an id property. Mongodb itself will automatically do the _id as a real BSON ObjectId, and mongoose will add id as a string representation of the same value, so don't worry about that.
While I don't understand your schema (and the circular nature of it?), this code works:
var order = new models.BuyOrder({ price: 100, quantity: 5});
order.save(function(err, orderDoc) {
var security = new models.Security();
security._bids.push(orderDoc);
security.save(function(err, doc) {
models.Security.findById({ _id: doc._id })
.populate("_bids").exec(function(err, security) {
console.log(security);
});
});
});
It:
creates a BuyOrder
saves it
creates a Security
adds to the array of _bids the new orderDoc's _id
saves it
searches for the match and populates
Note that there's not an automatic method for adding the document to the array of _bids, so I've done that manually.
Results:
{ _id: 5224e73af7c90a2017000002,
__v: 0,
_asks: [],
_bids: [ { price: 100,
quantity: 5,
_id: 5224e72ef7c90a2017000001, __v: 0 } ] }

Resources