Mongo Set One Table Column as One Table's Option - mongodb

Expecting a solution for this scenario. I have two tables. table 1 'team' contains'team_name' and table 2 'players' contains 'players_name' and 'players_team'. So, Here I want to insert data into players table. If I am inserting players_team in players table it should be a valid team name which exists on team table. How can I achieve this?
Note: This can be achieved by simply checking for the value in column first, But That is not what am looking for. I know in MySQL there is a method where the value of one's can be linked someway. I want to know whether the same can be achieved with mongo and mongoose

Your answer
router.post('/add_player', (req, res) => {
let teamid = req.body.teamid;
Teams.findOne({ _id: teamid }, (err, Team) => {
if (err) {
console.log(err)
} else {
if (Team == null) {
console.log("Team not found")
} else if (Team != null) {
console.log("Team Found")
//Add Player
let Data = {
players_team: teamid,
team_name: Team.team_name,//Valid team name
player_name: req.body.player_name,
}
Players(Data).save((err, SaveResult) => {
if (err) {
console.log(err);
} else {
console.log('player saved successfully')
res.status(200).send('player added successfully')
}
})
}
}
})
})

Related

I am having trouble reading a FireStore document file through DialoFlow ES

We are trying to read a document file from Firestore through Dialogflow. We get as far as "I can't find your reservation." Each document's id is auto generated, so we can't match from the Document ID field (or at least do not know how to). Any help would be greatly appreciated!
Fulfillment function code:
function readReservation(agent) {
let id = agent.parameters.name.toString();
let collectionRef = db.collection('reservations');
let userDoc = collectionRef.doc(id);
return userDoc.get()
.then(doc => {
if (!doc.exists) {
agent.add('I could not find your reservation.');
} else {
db.collection('reservations').doc(id).update({
newname: agent.parameters.newname
}).catch(error => {
console.log('Transaction failure:', error);
return Promise.reject();
});
agent.add('Ok. I have updated the name on the reservation.');
}
return Promise.resolve();
}).catch(() => {
agent.add('Error reading entry from the Firestore database.');
});
}
I have tried different ways to write this code, but was unsuccessful.

.find() returning nothing even when data exists

I've a mongo database with 3 collections for 3 different kind of users as User,Partner,Admin. Whenever a new user of any type signup I'm searching all three collections to check if username and email exist already. I'm trying to achieve this by calling a function as:
function checkAttribute(attr,val,callback){
User.find({attr: val},function(err,user){
if(err){
console.log(err);
}else{
if(user.length === 0){
Partner.find({attr: val},function(err,partner){
if(err){
console.log(err);
}else{
if(partner.length === 0){
Admin.find({attr: val},function(err,admin){
if(err){
console.log(err);
}else{
if(admin.length === 0){
return callback(null,true);
}else{
return callback(null,false);
}
}
});
}else{
return callback(null,false);
}
}
});
}else{
return callback(null,false);
}
}
});
};
Calling function line:
checkAttribute("username",newUser.username,function(error,response){
.......
});
But this is not working as it returns true always even when users with passed username/email exists already. I am unable to find the problem. Any one knows why this is happening?
Thanks in advance.
Since you are passing in the attribute as a variable in the function parameters, the query document
{ attr: val } is an object with the key "attr", not the dynamic attribute you pass in.
To fix this, you need to use computed property names in your query object as
{ [attr]: val }
Also, the function can use async/await pattern to be more readable and for the purpose of finding if a document exist findOne does the job so
well as it returns a document if it exists and null otherwise.
So your function can be refactored as
async function checkAttribute(attr, val, callback) {
try {
const query = { [attr]: val }
const user = await User.findOne(query).exec()
const partner = await Partner.findOne(query).exec()
const admin = await Admin.findOne(query).exec()
const found = (user || partner || admin) ? true: false
return callback(null, found)
} catch (err) {
console.error(err)
return callback(err, null)
}
};
attr: in your queries will search for a db field called attr. If you want to use the function parameter attr, use [attr]: as the key.
Example:
attr = 'username'
User.find({ [attr]: val }, function (err, user) {
if (err) {
console.log(err);
}
})
This is a feature available since ES6 so should work fine. See the docs here for more info

Issue with getting information from mongodb

Ok so here is what I am trying to do, I have a Item collection that holds a users items along with price quantity and description. I have also created a collection called soldItems that will store information about a sold item once the user inputs the required data and submits the form. I am not sure if I am doing this correctly to begin with and I have been trying to research this but I don't exactly know what I am looking for.
Here is the code I have so far
router.post("/item/:id", middleware.isLoggedIn, (req, res) => {
Item.findById(req.params.id, (err, item) => {
if(err) {
console.log(err);
}
var soldItem = {
id: req.params.id,
item: req.item.name,
askPrice: req.item.price
};
var soldPrice = req.body.soldPrice;
var soldQuantity = req.body.soldQuantity;
var itemSold = {
soldItem: soldItem,
soldPrice: soldPrice,
soldQuantity: soldQuantity
};
SoldItem.create(itemSold, (err, newlyCreated) => {
if (err) {
console.log(err);
} else {
item.soldItems.push(newlyCreated);
item.save();
req.flash("success", "Item Sold");
res.redirect("back");
}
});
});
});
So... Item.findById(req.params.id) works because I am pulling the ObjectId from the url. However, how would I be able to use req.item._id. Because the issue I am having is when I am trying to get req.item.name and req.item.price I am being told that it cannot read property 'name' or 'price' of undefined. How can I get that information?

How to replace a manual id with an ObjectID _id in mongoDB?

Let's say I have a database with two collections, kids and classes. Each kid belongs to one class.
Each class has a previously created integer id.
I want to replace the kid.class_id with the (ObjectID) _id of the class, not the (integer) id of the class.
However, when I run the script below, it doesn't reset the class_id with the class._id -- it remains the old integer id.
mongoose.connect(someMongodbUri, { useMongoClient: true }, (err, db) => {
let kidsCount = 0;
db.collection('kids').find({}).each((err, kid) => {
kidsCount++;
db.collection('classes')
.findOne({ id: kid.class_id })
.then((class, err) => {
let newClassId = class._id;
db.collection('kids').updateOne(
{ _id: kid._id },
{ $set: { class_id: newClassId } }
).then(() => {
console.info('Updated', kid.class_id);
kidsCount--;
if (kidsCount === 0) { db.close(); }
});
});
});
});
Am I missing something? Thanks for any help you can offer!
We can convert integerId to Object id.
var ObjectId = require('mongodb').ObjectID;
let newClassId = ObjectId(class._id);
There may be better or elegent ways that i don't know, but this works for me.

How can we achieve Joins in MongoDB?

I have two collections in db,
1. products (product_id, name, status, price, unit_price)
2. cart_details (cart_id, product_id, quantity)
Problem I am facing is, I want to show descriptive record on cart details page from these both collections. Where unit_price and product_name will come from products collection while quantity will be used from cart_details collection. I referred Mongo DB's own documentation it do returns me collection with nested objects but problem with that is if i want to update quantity in cart_details collection it throw an exception of "type mismatch".
Don't know if there is any other way to join tables and on update of one collection it won't throw any error.
here is the update cart code.
exports.update = function(req, res) {
var cart = req.cart;
cart = _.extend(cart, req.body);
cart.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(cart);
}
});
};
and here is the cart service:
angular.module('core').factory('Cart', ['$resource',
function($resource) {
return $resource('cart/:cartId', { cartId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
]);