findOneAndUpdate doesn't make update - node.js

I am using mongoose with mean stack, I want to add a column age to my data saved in the database which contains a value of email 'a#a.a'
var MyModel = db.model('MyModel', userSchema);
var query = {'email' : 'a#a.a' };
MyModel.findOneAndUpdate(query,{ 'age': '20' } , {upsert:true},function(err, doc){
if (err) return res.send(500, { error: err });
//return res.send("succesfully saved");
console.log('check');
});
but when I run in the mongo shell db.users.find({"email" : "a#a.a" }) I can't see the column added

I don't need the variable MyModel, :
User.findOneAndUpdate(query,{ age: 'age1' } , {upsert:true},function(err, doc){

Related

Search if providing id is exist on Multiple objects under array mongodb

My Database having this value
id: ObjectId(6a00683bac41ce1054774e7d),
currentuserid: "69fc06dbf88c8c15042b4e36",
dataset: Array
0: Object
userid: "69fc06dbf88c8c15042b4e37"
1: Object
userid: "69fc06dbf88c8c15042b4e38"
2: Object
userid: "69fc06dbf88c8c15042b4e39"
Now I want to make query which first Check That "currentuserid" is Exist under array. if Value exist then returns true else false. I am new in mongodb. I also read $in Operator . My query is
Mydata.find({ dataset: { $in: [{userid: '69fc06dbf88c8c15042b4e36'}] } }, function(req, res){
if(err){ console.log('Not Matched'); }
else{ console.log('Matched') }
});
But i am unable to achieve it
Try this:
Mydata.findOne({dataset:{$elemMatch:{userid:'69fc06dbf88c8c15042b4e37'}}},function(err, data){
if(err){
throw err;
} else if(data){
console.log('Matched');
}else{
console.log('Not Matched')
}
});
It will result data as null for userid 69fc06dbf88c8c15042b4e36.

mongoose findOne data does not exit not working

user_id 2 does not exist in mongodb but console log does not print 'does not exist'
var query = PostData.findOne({ 'user_id': '2'});
query.exec(function (err, doc) {
if(doc) {
console.log('ok');
} else {
console.log('does not exist');
}
});
Without mongoose it works:
connection.db.collection("PostData", function(err, collection){
collection.find({ 'user_id': '2'}).toArray(function(err, data){
console.log(data); // it will print your collection data
})
});
prints []
No matter an object exists or not , MongoDB is going to return an array anyway. If the object exists, they array will be filled with it otherwise it's just an empty array. So if you want to check if the user exists or not you must check for doc.length , if it's 0 then it means the user doesn't exist.

Mongoose findByIdAndUpdate not returning correct model

I have an issue I've not seen before with the Mongoose findByIdAndUpdate not returning the correct model in the callback.
Here's the code:
var id = args._id;
var updateObj = {updatedDate: Date.now()};
_.extend(updateObj, args);
Model.findByIdAndUpdate(id, updateObj, function(err, model) {
if (err) {
logger.error(modelString +':edit' + modelString +' - ' + err.message);
self.emit('item:failure', 'Failed to edit ' + modelString);
return;
}
self.emit('item:success', model);
});
The original document in the db looks like this:
{
_id: 1234
descriptors: Array[2],
name: 'Test Name 1'
}
The updateObj going in looks like this:
{
_id: 1234
descriptors: Array[2],
name: 'Test Name 2'
}
The model returned from the callback is identical to the original model, not the updatedObj.
If I query the db, it has been updated correctly. It's just not being returned from the database.
This feels like a 'stupid-user' error, but I can't see it. Any ideas greatly appreciated.
In Mongoose 4.0, the default value for the new option of findByIdAndUpdate (and findOneAndUpdate) has changed to false, which means returning the old doc (see #2262 of the release notes). So you need to explicitly set the option to true to get the new version of the doc, after the update is applied:
Model.findByIdAndUpdate(id, updateObj, {new: true}, function(err, model) {...
app.put("/vendor/:id",async (req,res)=>{
res.send(req.params)
await ModelName.findByIdAndUpdate(id, {type: change}, function(err, docs){
if(err){
conslole.log(err)
}else{
console.log(docs)
}
})
})
Example:
app.put("/vendor/:id",async (req,res)=>{
res.send(req.params)
const data = await userModel.findByIdAndUpdate(req.params.id, {isVendor: true},
function(err, docs){
if(err){
conslole.log(err)
}else{
console.log(docs)
}
})
})

Node.js mongodb update over ObjectID

I want to update my Document but it's not working 100% .
// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/testDB", function(err, database) { //"mongodb://localhost:27017/test"
if(err) throw err;
db = database;
});
My collection row looks like:
{ "_id" : ObjectId("53f9379ce9575bbe9ec29581"), "name:paco",
"status:student" }
Now if I want to update the row over the Document as follows:
db.collection('user', function(err, collection){
collection.update({'_id':ObjectID(req.session.loggedIn)}, {image : filename}, {w:1}, function(err, result){
console.log(result);
I am getting just:
{ "_id" : ObjectId("53f9379ce9575bbe9ec29581"), "image:filename" }
How can I make an update to get my data like this??:
{ "_id" : ObjectId("53f9379ce9575bbe9ec29581"), "name:paco",
"status:student" , "image:filename"}
Doing an update the way you did it is going to retrieve the document in your collection with the specified _id, then it is going to replace the content of this document with what you specified as your second parameter. In your case, it will retrieve the document with _id 53f9379ce9575bbe9ec29581, and replace the existing fields with the field you passed, image:filename (that means the existing fields will be removed, as you noticed).
What you want to do is use the $set operator. This operator will not touch the document retrieved, but only modify the field that you specified, or add it if it does not exist.
So your update command should look something like this:
db.collection('user').update({'_id':ObjectID(req.session.loggedIn)}, {$set: {image : filename}}, {w:1}, function(err, result){
console.log(result);
to update record by _id
var ObjectID = require('mongodb').ObjectID;
exports.updateUser = function(req, res) {
var collection = db.collection('users');
collection.update(where, $set:req.body, function(err, result) {
if (err) {
console.log('Error updating user: ' + err);
res.send({'error':'An error has occurred'});
} else {
console.log('' + result + ' document(s) updated');
res.send(user);
}
});
}

How to update document in mongo with nested schema

I have the following code:
add_new_patient : function(username,pname,pid,pdesc,callback){
var find_md = function(){
return function(err,pat){
if (err){
console.log('Error at adding patient: error at searching for users');
callback(2);//In the callback method I'm passing I have specific behavior for error handling for error codes.
return;
}
if (pat.lenth > 0){
console.log('searching for md');
MD.find({'mdname':username},add_patient(pat));
}else{
console.log('Error at adding patient: no user found');
callback(-1);
return;
}
}}
var add_patient = function(pat){
return function(err,md){
if (err){
console.log('Error at adding patient: cannot find md');
callback(-1);
return;
}
callback(0);
}
}
console.log('searching for user '+pid);
User.find({'name':pid},find_md());
}
And these are my schemas:
var mdSchema = mongoose.Schema({
mdname : String,
pacients : [userSchema.ObjectId]
});
var userSchema =mongoose.Schema({
name : String,
password : String,
phone : String,
history : [{timestamp: Date , heart: Number }],
md : {mdname: String, contact: Number}
});
As you can guess from the code I want to add patients to the dms. First I search for the pid in the database. If I find a patient I start to look for mds. When I find the md I want to add the patient to the md. Now I don't know how to add them. The schema shows that I have an array of schemaUser, which is the type of patient, but I don't know how to append to it, not how to create an MD model from object from the data I received from the query. Also what should I insert into the array of patients? The _id of the found patient or the whole object?
I managed to solve it in the following way:
var add_patient = function(pat){
return function(err,md){
if (err){
console.log('Error at adding patient: cannot find md');
callback(-1);
return;
}
var query = {mdname: md.mdname};
console.log(md);
var doThis = { $addToSet: { patients: pat._id } };
console.log(query);
MD.update(query,doThis,done_adding());
}
}
var done_adding = function(){
return function(err,dat){
if (err){
console.log('Error at the end of adding new patient!');
callback(-1);
return;
}
console.log('new patient added');
callback(0);
}
So what this does is: when I have the md to whom I want to add a patient/user I use the update method, with the $addToSet operation so I will have a set of patients associated with an md. I don't know why, but the same code did not work for me with the $push parameter. Then simply nothing happened and when I set the upsert option to true my whole record in the database was overwritten by the id.

Resources