return single object based on ObjectId - javascript

hi im currently building something for fun that allows users to post anything. and im experincing some problems here is my code.
return details.findOne({'data': {$elemMatch: {'_id':req.params.id}}}).then((a) => {
return res.render('post', { a });
}).catch(err => console.log(err));
i only want this to return one post i thought by using the objectId id would be able todo that but it seems to return everything in the data array anybody have any ideas below is my schema.
i need this to only return the single object whos objId is in the url
var schemaMode = new mongoose.Schema({
email: {type: String, required: true},
password: {type: String, required: true},
username: {type: String,required:true},
data: [{
author: String,
title: String,
comments: [String],
article: String,
}]
});

Details.findById(req.params.id, function(err, foundObject){
//foundObject contains the object with the ._id matching req.params.id
});
if you only want certain fields back, like you want the object to only have its data field for example, then you do:
Details.findById(req.params.id, "data",
function(err, foundObject){
//foundObject contains the object with the ._id matching req.params.id
});
OR
Details.findById(req.params.id).select("data")
.exec(function(err, foundObject){
//foundObject contains the object with the ._id matching req.params.id
});
to be clear, in the code above, Details is the imported (with require) schema (in your case, the one named schemaMode)

Is "data" your "post"? If so, I think you need a projection.
return details.findOne({'data': {$elemMatch: {'_id':req.params.id}}},{'data.$'}).then((a) => {
return res.render('post', { a.data[0] });
}).catch(err => console.log(err));
'data.$' will project you the whole model, filled only with the desired "data"/"post"

Related

Unable to save a array correctly in mongoodb using node/mongose

What is the proper way to save an array of data in mongodb using node/mongoose?
I am able to all my data as an array, but everything is saved as the first value in the array (see img)
this is my current code:
const channel = new Channel({
// other fields
fields:req.body.fields,
creator: req.userData.userId //fix: creator not being passed
});
channel
.save()
.then(createdChannel => {
res.status(201).json({
message: "Channel added successfully",
channel: {
...createdChannel,
id: createdChannel._id
}
});
})
.catch(error => {
console.log('error',error)
res.status(500).json({
message: "Creating a channel failed!"
});
});
here is my data model:
const mongoose = require("mongoose");
const channelSchema = mongoose.Schema({
// other fields
fields: { type: [String], required: true },
creator: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true }
});
module.exports = mongoose.model("Channel", channelSchema);
I didn't see a similar issue online.
Any idea on how I am suppose to save an array properly?
Looks like your req.body.fields is stringified. So, you should parse it back to JSON:
const channel = new Channel({
fields: JSON.parse(req.body.fields),
creator: req.userData.userId,
});
This is because you are setting fields value as an array of strings, regarding to this question you should define your schema as:
fields : [{foo: String, bar: string}]
or if you don't know what attributes you will have in the object:
fields: {"type": Array, "default": []}
Hope this can help you

mongoose populate doesn't work with array of IDs

I have these two 3 models User, Product and Orders and are also has references to each other.
My Orders Schema:
const orderSchema = Schema({
buyerId:{
type: Schema.Types.ObjectId,
ref: 'User'
},
totalAmount: {
type: Number,
required: [true, "description is required"]
},
createdOn: {
type: Date,
default: new Date()
},
items:[{type:Schema.Types.ObjectId, ref: 'Product'}]})
I'm trying to use populate() like this:
Order.find()
.populate('buyerId')//Reference to User Model
.populate('items')// Reference to Product Model
.exec(function (err, result){
console.log(result);// RETURNS ONLY buyerId populated
console.log(result.buyerId.name);//Successfully references to my User model and prints name
console.log(result.items);//Prints Undefined
})
You can see my console log above and what it returns is only the populated buyerId(only got the reference from my User model)
Seems like my populate('items') doesnt work at all. The items field contains array of IDs, where the IDs are those of products. I need to reference to User and Product both. I'm just following the documentation in mongoose, I don't know what I might be doing wrong.
use aggregate
Order.aggregate([
{ $match:{ user:"sample_id"
}
},
{$lookup:{
from:'users', // users collection name
localField:'buyerId',
foreignField:'_id',
as:'buyerId'
}},
{
$lookup:{
from:'items', //items collection name
localField:'items',
foreignField:'_id',
as:'items'
}
},
])

How can I add to this schema array with mongoose?

Here's the user schema and the part I want to update is ToDo under User.js (further down). I am attempting to add new data to an array within the db.
data.js
app.post("/data", loggedIn, async (req, res) => {
console.log(req.body.content);
let content = { content: req.body.content };
User.update({ _id: req.user._id }, { $set: req.body }, function (err, user) {
if (err) console.log(err);
if (!content) {
req.flash("error", "One or more fields are empty");
return res.redirect("/");
}
user.ToDo.push(content);
res.redirect("/main");
});
});
User.js
new mongoose.Schema({
email: String,
passwordHash: String,
ToDo: {
type: [],
},
date: {
type: Date,
default: Date.now,
},
})
Originally I was trying the .push() attribute, but I get the error:
user.ToDo.push(content);
^
TypeError: Cannot read property 'push' of undefined
First of all, your problem is the callback is not the user. When you use update the callback is something like this:
{ n: 1, nModified: 1, ok: 1 }
This is why the error is thrown.
Also I recommend specify the array value, something like this:
ToDo: {
type: [String],
}
The second recommendation is to do all you can into mongo query. If you can use a query to push the object, do this instead of store the object into memory, push using JS function and save again the object into DB.
Of course you can do that, but I think is worse.
Now, knowing this, if you only want to add a value into an array, try this query:
var update = await model.updateOne({
"email": "email"
},
{
"$push": {
"ToDo": "new value"
}
})
Check the example here
You are using $set to your object, so you are creating a new object with new values.
Check here how $set works.
If fields no exists, will be added, otherwise are updated. If you only want to add an element into an array from a specified field, you should $push into the field.
Following your code, maybe you wanted to do something similar to this:
model.findOne({ "email": "email" }, async function (err, user) {
//Here, user is the object user
user.ToDo.push("value")
user.save()
})
As I said before, that works, but is better do in a query.

Mongoose find by parameters including sub-array

I am creating an app where a job is created and that job's id is added to another collection (client) so the job can be referenced from the client itself. I have been able to add the job's id to the client's collection so far, but I am having trouble figuring out how to remove the job's id from the client's collection if the job is deleted. This is because the id is stored as a sub-collection within the client. The code I am trying to get to work is below:
// delete
app.delete("/jobs/:id", function(req, res){
Client.find({jobs._id: req.params.id}, function (err, foundClient){ //This part doesn't work
if (err) {
console.log(err);
} else {
// Add id identifier to Client
foundClient.jobs.pull(req.params.id);
foundClient.save();
}
});
// Delete Job
Job.findByIdAndRemove(req.params.id, function(err, deletedJob){
if (err){
console.log(err)
} else {
// Redirect
res.redirect("/jobs");
}
});
});
I am trying to get the logic of this part to work:
Client.find({jobs._id: req.params.id},
Here is the Client Schema
// =======================Client Schema
var clientSchema = new mongoose.Schema({
organization_name: String,
first_name: String,
middle_name: String,
last_name: String,
email_address: String,
phone_number: String,
street: String,
city: String,
state: String,
zip: String,
description: String,
active: {type: Boolean, deafult: true},
date_added: {type: Date, default: Date.now},
transactions: [{type: mongoose.Schema.Types.ObjectID, ref: "Transaction"}],
jobs: [{type: mongoose.Schema.Types.ObjectID, ref: "Job"}]
});
module.exports = mongoose.model("Client", clientSchema);
Basically, what I am trying to tell it to do is find the Client where the client's jobs array contains an id equal to the id of the job being deleted. Of course, this syntax is incorrect, so it does not work. I have not been able to find documentation that explains how I would be able to do this. Is there a more straightforward way of doing this, the way I am writing it out here? I know that I can query the db this way if the job itself was not an array and only contained one singular variable. Is there a way to do this or do I need to write a completely separate looping function to get this to work? Thank you.
jobs is an array of ids, so to find some documents in Client collection that have req.params.id in the jobs array, the query should be something like this
Client.find({jobs: req.params.id})
this will return an array of documents, each document has an array of jobs Ids
If you are sure that the req.params.id exists only in one document, you can use findOne instead of find, and this will return only one document with an array of jobs Ids
this is regarding the find part
regarding the remove job Id from jobs array, we can use one of the following methods
1- as you suggested, we can find the clients documents that have this job Id first, then remove this id from all the jobs arrays in all matching documents
like this
Client.find({ jobs: req.params.id }, async function (err, foundClients) {
if (err) {
console.log(err);
} else {
// loop over the foundClients array then update the jobs array
for (let i = 0; i < foundClients.length; i++) {
// filter the jobs array in each client
foundClients[i].jobs = foundClients[i].jobs || []; // double check the jobs array
foundClients[i].jobs = foundClients[i].jobs.filter(jobId => jobId.toString() !== req.params.id.toString());
// return all the jobs Ids that not equal to req.params.id
// convert both jobId and req.params.id to string for full matching (type and value)
await foundClients[i].save(); // save the document
}
}
});
2- we can use $pull array update operator to update the jobs array directly
something like this
Client.updateMany(
{ jobs: req.params.id }, // filter part
{
$pull: { jobs: { $in: [req.params.id] } } // update part
},
function (err) {
if (err) {
console.log(err);
} else {
console.log('job id removed from client documents successfully');
}
}
);
hope it helps

Mongoose's lean usage with populate and nested queries

Im coding an app in Node.js which is using MongoDB. I chose MongooseJS to handle my DB queries.
I have two collections that are referenced to each other (Room which is the 'superior' collection and DeviceGroups which is contained within Room collection).
I have a query that gets a list of all of the rooms from Room collection, populates deviceGroups field (which is the Rooms reference to DeviceGroup collection) and inside it there is a map method that goes through every room found in the Room collection and for every room it makes another query - it looks for any deviceGroups in DeviceGroup collection that are referenced to the current room in the map method.
My goal here is to return a list of all of the rooms with deviceGroups field filled in with actual data, not only references.
What I am getting after the queries (inside the then method) is a Mongoose document. The whole algorithm is used as a handler of a GET method, so I need a pure JavaScript object as a response.
Main goal I want to achieve is to get result of all of the queries and population inside them as pure javascript object, so I can create a response object and send it (i dont want to send everything that db returns, because not all of the data is needed for this case)
EDIT:
I am so sorry, I have deleted my code and didnt realize it.
My current code is below:
Schema:
const roomSchema = Schema({
name: {
type: String,
required: [true, 'Room name not provided']
},
deviceGroups: [{
type: Schema.Types.ObjectId,
ref: 'DeviceGroup'
}]
}, { collection: 'rooms' });
const deviceGroupSchema = Schema({
parentRoomId: {
type: Schema.Types.ObjectId,
ref: 'Room'
},
groupType: {
type: String,
enum: ['LIGHTS', 'BLINDS', 'ALARM_SENSORS', 'WEATHER_SENSORS']
},
devices: [
{
type: Schema.Types.ObjectId,
ref: 'LightBulb'
}
]
}, { collection: 'deviceGroups' });
Queries:
app.get('/api/id/rooms', function(req, res) {
Room.find({}).populate('deviceGroups').lean().exec(function(err, parentRoom) {
parentRoom.map(function(currentRoom) {
DeviceGroup.findOne({ parentRoomId: currentRoom._id }, function (err, devices) {
return devices;
});
});
}).then(function(roomList) {
res.send(roomList);
});
});
where are you confusing. here is a simple and effective code snippet
Room.findById(req.params.id)
.select("roomname")
.populate({
path: 'deviceGroup',
select: 'devicename',
model:'DeviceGroups'
populate:{
path: 'device',
select: 'devicename',
model:'Device'
}
})
.lean()
.exec((err, data)=>{
console.log(data);
})

Categories

Resources