Issue in inserting bulk data in nodejs - javascript

Here is my object,
{'name': 'Lipika', 'monday': 1}
{'name': 'Ram', 'monday': 0}
{'name': 'Lipika', 'tuesday': 1}
{'name': 'Ram', 'tuesday': 0}
Here is the two condition
I want to check whether Lipika is present in the DB, If not present i should create his name in the User Collection and then insert in the Attendance Collection, If Already present then i should just insert the Attendance Collection.
Here is what i have tried
for (var key in row) {
checkUser(name,function(data) {
//Insert inside Attendence collection then..
});
}
function checkUser(name, callback){
dbModel.User.findOne({ name: name}, function (err, data) {
if(data){
callback('exist');
}else{
var User = new dbModel.User({name : name});
User.save(function (err) {
if (err) {
console.log('Err',err);
} else {
callback('not exist');
}
});
}
});
}
But it is creating Lipika and Ram two times as nodejs run async way. How can i wait the until the javascript checks and insert inside the user ?

Try this code may be help you !
function checkUser(name, callback){
dbModel.User.findOne({ name: name}).then((data)=>{
if(data){
//callback('exist');
//user already present insert attendance
}else{
var User = new dbModel.User({name : name});
User.save().then((data)=>{
//user not present insert collection
},(err)={
});
}
},(error)=>{
console.log('something went wrong');
});
}

Instead of everytime checking in DB why don't you make name field unique, That will give the more accurate result. Because Reading and writing will create the problem if multiple requests will come at same time.
Use findAndModify to avoid 2 operation reading and writing. Not Good approach :(
dbModel.User.findAndModify({
query: {
name: name
},
update: {
$setOnInsert: {
name: name
}
},
new: true,
upsert: true
}, (err, data) => {
callback('exist');
});

Related

MongoDB update many using the values of the user

I've written a function to execute hourly which looks up a user and finds some values and then pushes those values into a history collection that records the hourly updated values. I've written this so far as a test just finding a user by their ID but now I need to roll this out to my entire database of 50,000+ users.
From what I've read using updateMany is a lot more performant but I'm not entirely sure how to retrieve the document detail of the record that is being updated at the time.
Here is my code so far, which you can see I'm first looking up the user and then grabbing their valuation details which I'd like to then push into a history collection.
exports.updateUserValuationHistoric = () => {
User.find({ _id: "609961fdd989613914ef7216" })
.populate('UserValuationHistory')
.exec((err, userDoc) => {
if (err){
console.log('[ERROR]: ', err)
}
const updatedValuationHistory = {
totalValuation: userDoc[0].valuation.totalValuation,
comicsValuation: userDoc[0].valuation.comicsValuation,
collectiblesValuation: userDoc[0].valuation.collectiblesValuation,
omiValuation: userDoc[0].valuation.omiValuation
}
UserValuationHistory.findOneAndUpdate(
{ user: userDoc[0]._id },
{ $push: {
'history': updatedValuationHistory
}},
{upsert: true, new: true}
)
.exec((error, updated) => {
if (error){
console.log('[ERROR]: Unable to update the user valuation history.')
} else {
console.log('[SUCCESS]: User historic valuation has been updated.')
}
})
})
}
Any help is greatly appreciated!
User model:
https://pastebin.com/7MWBVHf3
Historic model:
https://pastebin.com/nkTGztJY

MongoDB update with condition - update based on other existing field value

RELATED TO THIS: MongoDB update with condition
https://stackoverflow.com/a/62816731/15931755
This is my first time using this site to post so bare with my structure.
QUESTION: I need to update a mongodb collection field ex: collectionName.gender based on the current values of some other field (or the same field) ex: collection.gender
This was a PUT route for me
Original post was missing a few pieces, this is the full code block for anyone who needs the full PUT route.
ANSWER:
exports.someName = function (req, res) {
db.customer.updateMany(
{},
[
{
$set: {
gender: {
//if you need need to $set a nested field I replaced gender with 'parentfield.gender'
$switch: {
branches: [
{case: {$eq: ['$gender', 'male']}, then: 'female'},
{case: {$eq: ['$gender', 'female']}, then: 'male'}
//you can add more conditions, I used 4 conditions
],
default: ''
}
}
}
}
], function (err, doc) {
console.log(doc)
})
res.status(200).json({success: 1, message: 'successfully updated based on conditions'})
}
// good luck and remember to keep answering
This is the way. Same as above.
exports.someName = function (req, res) {
db.customer.updateMany(
{},
[
{
$set: {
gender: {
//if you need need to $set a nested field I replaced gender with 'parentfield.gender'
$switch: {
branches: [
{case: {$eq: ['$gender', 'male']}, then: 'female'},
{case: {$eq: ['$gender', 'female']}, then: 'male'}
//you can add more conditions, I used 4 conditions
],
default: ''
}
}
}
}
], function (err, doc) {
console.log(doc)
})
res.status(200).json({success: 1, message: 'successfully updated based on conditions'})
}

TypeError: Cannot read property 'push' of undefined, i can't push comments to data array

I can't push comments to the data array. the comments have been created (they have been added to comment collection). How can I push them to data array? Here are some screenshots of my code: Comments Schema and
,The comments array is empty,
Camp Schema
var mongoose = require("mongoose");
var camp = require("./models/camp");
var Comment = require("./models/comment");
var data = [
{
name: "Cloud's Rest",
image: // a link goes here
},
{
name: "Desert Mesa",
image: //
},
{
name: "Canyon Floor",
image: //
}
];
function seedDB(){
//Remove all campgrounds that existed in the database & create new campgrounds with data array.
camp.remove({}, function(err){
if(err){
console.log(err);
}
console.log("removed campgrounds!");
//add a few campgrounds
data.forEach(function(seed){
camp.create(seed, function(err, camp){
if(err){
console.log(err)
} else {
console.log("added a campground");
//create a comment
Comment.create(
{
text: "This place is great, but I wish there was internet",
author: "Homer"
}, function(err, comment){
if(err){
console.log(err);
} else {
camp.comments.push(comment);
camp.save();
console.log("Created new comment");
}
});
}
});
});
});
//add a few comments
}
module.exports = seedDB;
EDIT: This answer presumes the syntax error is due to a missing }); after the camp.remove() function.
Without knowing what Camp looks like, I will presume that camp.create() will pass the definition of a camp to the callback method. If that is the case, then it would appear you need to use campground rather than camp since it would appear that the new camp is passed into that callback function as campground.

Finding a document, editing it, and putting it back in MongoDB

I am using mongodb and I want to be able to edit a document and reinsert it WITHOUT duplicates. So far i have tried collection.findAndModify() but I couldn't get that to work. I have a collection like this:
UserProfiles = [
{
userProfileID: 1,
firstName: 'Austin',
lastName: 'Hunter',
email: 'ahun.....com',
token: '',
platform: '',
password: 'incorrect',
companyProfileID: 1,
authentication: '',
UserTopics: [
I want to be able to do this:
1 - grab the profile out of the object via searching for email match.
2 - when the email matches, edit the token and platform item.
3 - then put the document back in with no duplicates. So I can't just insert it again because that duplicates it.
Can anyone help me out on figuring this out?
Code:
function registerUser(email, token, platform) {
MongoClient.connect(url, function(err, db) {
if (err) {
console.log(err);
} else {
console.log("We are connected");
}
var collection = db.collection('UserProfile');
collection.findAndModify({
query: { email: email },
update: { token: token, platform: platform }
});
db.close();
modelname.findOneAndUpdate({ email: var_email}, { $set: { token: var_token, platform: var_platform}}, { new: true }, function(err, doc)
{
//doc here has updated document, in case you need it.
});
var_email etc. is your variable name and email is field name in
database.
{ new: true } - This part is used to fetch updated document, you can chose to not have this in your code but then you wont get updated document in response.

Mongoose update previously fetched collection

I would like to update a collection. Docs seem unclear on this.
I am wondering how to achieve the following:
Order.find({ _id: { $in: ids }}).exec(function(err, items, count) {
// Following gives error - same with save()
items.update({ status: 'processed'}, function(err, docs) {
});
});
I know how to batch save like this:
Model.update({ _id: id }, { $set: { size: 'large' }}, { multi: true }, callback);
But that requires setting my query again.
I've also tried:
Order.collection.update(items...
But that throws a max call stack error.
In mongoose, model.find(callback), return an Array of Document via callback. You can call save on a Document but not on an Array. So you can use for loop or forEach on the Array.
Order
.find({ _id: { $in: ids}})
.exec(function(err, items, count) {
items.forEach(function (it) {
it.save(function () {
console.log('you have saved ', it)
});
})
});

Categories