find all in mongoose - node.js

I have Schema With name score, and that have an iduser: req.session.user._id.
and I have more than one items with same iduser. I wanna to find all the items with the same iduser. and I use the
var users = await storescors16.find({ id }) id = res.session.user._id.
but that show me all the items in score !
My code
//schema
const storescor = new mongoose.Schema({
iduser: String,
level: { type: String, default: null },
day: { type: String, default: null },
date: { type: String, default: null },
time: { type: String, default: null },
objectif: { type: String, default: null }
})
var storescors16 = mongoose.model("storescor", storescor);
//post infos to database
router.post('/control/edite-control', (req, res) => {
console.log(req.session.selectuserid);
var { level, day, date, time, ob } = req.body
var scor = new storescors16({
iduser: req.session.selectuserid,
level: level,
day: day,
date: date,
time: time,
objectif: ob,
})
//read infos from databse
router.get('/result', auth, async(req, res) => {
var id = req.session.user._id
console.log(id);
var user = User.findById(id, (err, docs) => {
if (err)
console.log(err);
else
console.log();
})
var ids = req.session.user._id
var notes = await storescors16.find({ ids })
console.log(notes);
let scor = user.quiz
res.render('./options/result', {
notes: notes,
scor: scor,
title: 'سجل درجات النجم',
name: session.user.name,
email: session.user.email,
})
});
I use nodejs as backend

If you want to find all use findAll function with where.
const users = await storescors16.findAll({ id });
That if I understand you currect.

Related

Mongoose Nested Queries - find and updating two fields in different documents

What Im trying to do is have one user send an amount to another user, Id like for the amount to be subtracted from the sender's balance, and added to the receiver's balance. The problem is that the receivers balance is updated and works, but the previous query to subtract the amount from the sender isn't working.
I understand there are no joins in mongoose (at least not in the classical sense), so Id need to query the user's balance first and then update it in another query. But surely there is a way to nest these queries? Im hoping I just have the syntax wrong.
user.js
const { Decimal128 } = require("mongodb");
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const UserSchema = new Schema({
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
name: {
type: String,
required: true,
},
useraddress: {
type: String,
required: true,
},
userbalance: {
type: Decimal128,
required: true,
}
});
module.exports = User = mongoose.model("users", UserSchema);
server.js
app.post("/sendamount", function (req, res) {
var amount = 100;
var senderAddress = "Bob123";
var receiverAddress = req.body.receiver;
// Take amount from sender balance
User.findOne({useraddress:senderAddress}, (err, sub) => {
if (err) return handleError(err);
var mybalance = parseFloat(sub.userbalance)
console.log(mybalance)
User.findOneAndUpdate(
{ useraddress: senderAddress },
{ userbalance: mybalance - amount }),
// send to receiver balance
User.findOne({useraddress:receiverAddress}, (err, sub2) => {
if (err) return handleError(err);
var receiverbalance = parseFloat(sub2.userbalance)
console.log(receiverbalance)
// add amount to receiver's balance
User.findOneAndUpdate(
{ useraddress: receiverAddress },
{ userbalance: receiverbalance + amount },
function (err, data) {
if (err) res.send(err);
res.send(data);
console.log("found " + data)
}
)
})
})
})
Would someone mind checking my code? Thanks
try to this subtrack process
I added example field, you have this areas change
const asyncSubtrackProcess = async (id, amount) => await User.findOneAndUpdate({
_id: mongoose.Types.ObjectId(id),
userbalance: { $gt: 0 }
},
{
$inc: {
userbalance: - parseInt(amount)
}
});
const result = () => amounts.map(async item => await asyncSubtrackProcess(item.id, item.amount));
result();

Node express find and return response multple models

I'm fairly new to node & express, I'm trying to implement a register application.
I have 2 models, both models have one common field 'empID'.
const RegisterEntriesSchema = mongoose.Schema({
empID: Number,
registerType: String,
registerItemsQuantity: Number,
registerItemsDesc: String
}, {
timestamps: true
});
const RegisterEmpSchema = mongoose.Schema({
empID: Number,
empName: String,
empPhone: String,
empProj:String
}, {
timestamps: true
});
For my get call in which I need to merge the values, I get from RegisterEmpSchema with its corresponding
employee details from RegisterEmpSchema.
exports.findAllRegisterEntries = (req, res) => {
registerEntriesModel.find()
.then(result => {
var updatedResponse=[];
console.log(result[0].empID);
for(var i=0;i<result.length;i++){
registerEmpModel.find({ empID: result[i].empID })
.then(result2 => {
**//unable to access result here**
}).catch(err => {
console.log("exception catch called findAllRegisterEntries, find employee details "+err);
});
}
res.send(updatedResponse);
}).catch(err => {
res.status(500).send({
message: err.message || "Some error occurred while retrieving register."
});
});
};
I basically need to get register data and its corresponding employee data.
How do I modify my find() code to use the key empID and do a join query fetch?
I think you better use populate, add ref to empID inside RegisterEntriesSchema
const RegisterEmpSchema = new mongoose.Schema({
empID: Number,
empName: String,
empPhone: String,
empProj: String
}, {
timestamps: true
});
const registerEmpModel = mongoose.model('RegisterEmpSchema', RegisterEmpSchema, 'registerEmployeeCollection');
const RegisterEntriesSchema = new mongoose.Schema({
registerType: String,
registerItemsQuantity: Number,
registerItemsDesc: String,
empID: {
type: mongoose.Schema.Types.ObjectId,
ref: 'RegisterEmpSchema'
}
}, {
timestamps: true
});
RegisterEntriesSchema.index({ createdAt: 1 }, { expires: '525601m' });
const registerEntriesModel = mongoose.model('RegisterEntriesSchema', RegisterEntriesSchema, 'registerEntriesCollection');
module.exports = {
registerEmpModel, registerEntriesModel,
}
then use populate() to populate the RegisterEntriesSchema with correspondence empID
RegisterEntriesSchema.
find().
populate('empID').
exec(function (err, data) {
if (err) return console.log(err);
res.send(data);
});
check mongoose docs: https://mongoosejs.com/docs/populate.html

Find an existing id object in post web service bill

I want to find an existing id object when I post a bill, but I don't know how find it to save the bill. I want it works from back end and front end.
This is my bill model:
const mongoose = require("mongoose");
const { Schema } = mongoose;
const billSchema = new Schema({
number: Number,
date: { type: Date, default: Date.now() },
type: String,
local: String,
client: {
type: mongoose.Schema.Types.ObjectId,
ref: "clients"
},
provider: {
type: mongoose.Schema.Types.ObjectId,
ref: "providers"
},
detail: [
{
quantity: Number,
product: {
code: Number,
name: String,
price: Number
},
undertotal: Number
}
],
total: Number
});
module.exports = mongoose.model("bills", billSchema);
And this is my post service:
app.post("/api/bills", async (req, res) => {
const { number, type, local, detail, total } = req.body;
let existingClient = await Client.findById(Client._id);
if (!existingClient) {
return res.status(404).json({
message: "not found client"
});
}
let existingProvider = await Provider.findById(Provider._id);
if (!existingProvider) {
return res.status(404).json({
message: "not found provider"
});
}
if (
!existingClient._id ||
(existingClient._id &&
mongoose.Types.ObjectId() ===
(await Client.findById(existingClient._id).select("_id")))
) {
const clientId = mongoose.Types.ObjectId();
this.existingClient._id = clientId;
}
if (
!existingProvider._id ||
(existingProvider._id &&
mongoose.Types.ObjectId() ===
(await Provider.findById(existingProvider._id).select("_id")))
) {
const providerId = mongoose.Types.ObjectId();
this.existingProvider._id = providerId;
}
const bill = new Bill({
number,
date: new Date(),
type,
local,
client: clientId,
provider: providerId,
detail,
total
});
try {
let newBill = await bill.save();
res.status(201).send(newBill);
} catch (err) {
if (err.name === "MongoError") {
res.status(409).send(err.message);
}
console.log(err);
res.status(500).send(err);
}
});
The expected output is bill saved with client and provider ids but real output is an error message saying "cannot read property _id of undefined"
What is wrong?

Mongo db, how to give object _id another collection's document

I have 2 collections called User and Location. In User, there is a location _id and this is an Object. Id also references the location collection. My question is what did I do wrong? When I call getUser function I want to see user information and the user's location information. What I need to do ?
User Schema
module.exports = (function userSchema() {
var Mongoose = require('mongoose');
var userSchema = Mongoose.Schema({
name: {
type: String,
require: true
},
surname: {
type: String,
require: true
},
tel: {
type: String,
require: true
},
age: {
type: String,
require: true
},
mevki_id: {
type: String,
require: true
},
location_id: [{
type: Mongoose.Schema.Types.ObjectId,
ref: 'locations'
}]
});
var collectionName = 'users';
var User = Mongoose.model(collectionName, userSchema);
return User;
})();
User Controller
function userController() {
var User = require('../models/UserSchema');
this.createUser = function (req, res, next) {
var name = req.body.name;
var surname = req.body.surname;
var tel = req.body.tel;
var age = req.body.age;
var mevki_id = req.body.mevki_id;
var lok_id = req.body.lok_id;
User.create({
name: name,
surname: surname,
tel: tel,
age: age,
mevki_id: mevki_id,
lok_id: lok_id
}, function (err, result) {
if (err) {
console.log(err);
return res.send({
'error': err
});
} else {
return res.send({
'result': result,
'status': 'successfully saved'
});
}
});
};
this.getUser = function (req, res, next) {
User.find()
.populate('lok_id')
.exec(function (err, result) {
if (err) {
console.log(err);
return res.send({
'error': err
});
} else {
return res.send({
'USERS': result
});
}
});
};
return this;
};
module.exports = new UserController();
First, your schema is wrong:
var userSchema = new Mongoose.Schema({
// ...
location_id: { type: [Mongoose.Schema.Types.ObjectId], ref: 'locations' }
})
Second, in your schema the last field name is location_id while in your controller, you change it to lok_id.
So, fix this:
User.create({
// ...
location_id: lok_id
}
and this:
User
.find()
.populate('location_id')
UPDATE
In your json the last field name is location_id, therefore, fix this too:
this.createUser = function (req, res, next) {
// ...
var lok_id = req.body.location_id;
}

Schema declaration and subdocument

Can you tell me what i'm doing wrong ?
var ObjectId = Schema.Types.ObjectId;
var ProductSchema = new Schema({
name: { type: String, required: true },
price: { type: Number, required: true },
category : { type: String, required: true }
});
var OrderSchema = new Schema({
products: [{
product: {type: ObjectId, ref: 'Product'},
quantity: {type: Number}
}],
status: { type: String, required: true }
});
Product = mongoose.model('Product', ProductSchema);
Order = rmongoose.model('Order', OrderSchema);
OrderSchema.statics.addOrder = function (data, cb) {
// data: array of products ID
var newOrder = new Order();
data.data.forEach(function(element, index, array) {
Product.findOne({ '_id': element.id }, function (err, product) {
if (err) return handleError(err);
newOrder.products.push({product: product, quantity: element.quantity});
})
});
newOrder.status = 'waiting';
newOrder.save(function (err, order) {
if (err) cb(err, false);
console.log(order);
var response = json.stringify({
event: 'addOrder',
success: true,
data: order.id
});
cb(false, response);
});
}
When i add an order products, array is always empty but i have no error. Maybe it's the wrong to do what i want.
Data send by the client are good and the foreach and findOne work well but push seems doing nothing.
If there is no solution maybe you can try to help me to find another solution.
Thanks :)
That's because you need to wait for all the products to be found.
Try this (untested):
OrderSchema.statics.addOrder = function (data, cb) {
// data: array of products ID
var newOrder = new Order();
var productIds = [];
var quantity = [];
data.data.forEach(function(element, index, array) {
productIds.push(element.id);
quantity.push(element.quantity);
});
Product.find({ '_id' : { $in: productIds} }, function(err, products) {
if (err) return handleError(err);
products.forEach(function(product, index) {
newOrder.products.push({product: product, quantity: quantity[index]});
});
newOrder.status = 'waiting';
newOrder.save(function (err, order) {
if (err) cb(err, false);
console.log(order);
var response = json.stringify({
event: 'addOrder',
success: true,
data: order.id
});
cb(false, response);
});
});
});

Resources