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.
Related
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.
I have multiple document in collection having a long string in each document, I want to retrieve one document at time, I dont have anything in document except long string, how can I retrieve that?
I inserted all document in collection using insertMany(), here is my code and output when I retrieved all document
var schema = new mongoose.Schema({
question : String,
id: Number
})
var quizz = mongoose.model('Quiz', schema );
var firstDoc = new quizz({
question: 'question 1',
id: 1
})
var secondDoc = new quizz({
question: 'question 2',
id: 2
var question_data = [firstDoc, secondDoc];
quizz.insertMany(question_data, function(err, res){
if(err){
console.log("error occured while saving document object " + err )
}else{
console.log("saved data");
}
})
quizz.findOne({id : '1'}, function(err, res){
if(err){
console.log(err)
}else{
console.log(res);
}
})
insertMany Will return you the list of _ids that have been created for your documents you've inserted. You can then pull out each document based on the _ids individually
quizz.insertMany(question_data, function(err, res){
if(err){
console.log("error occured while saving document object " + err )
}else{
console.dir(res); // res has the _ids.
console.log("saved data");
}
})
http://mongoosejs.com/docs/api.html#model_Model.insertMany
Alternatively if you always want to ensure ordering you could add a sequence column to the question, and/or put all questions inside one quizz.
if you want to do something with the _id of the documents that was inserted into the collection then use the answer of Kevin, but if you want to just do something with them later, you can use .find() which return you all the documents that are in the collection.
quizz.find(function(err, docs) {
//docs = array of all the docs in the collections
})
if you want specific by id:
quizz.findOne({_id: id},function(err, doc) {
//doc = the specific doc
})
if you want specific by strong
quizz.findOne({question: "question 3"},function(err, doc) {
//doc = the first (!!!) doc that have question in his `question` attribute
})
or if you want all the docs that have question 3 in them:
quizz.find({question: "question 3"},function(err, docs) {
//docs = array with all the docs that have "question 3" there, (return array even if only 1 found)
})
I wanted to delete a document with concerned _id and email when I click on "Remove task" in the HTML file.
Following is the code which removes that task:
I've passed value of email and _id(only hexadcemial string value) to the code:
collection.findOneAndDelete({email:email,_id:taskid},function (err, result) {
if (err) {
console.log(err);
} else {
console.log("Removed!");
console.log(result);
callback(result);
}
db.close();
});
But, the function is not recognizing _id that I've passed. The value of "taskid" variable is 566836bd8db43d3d56e23a4a i.e. only strings value from _id:
ObjectId("566836bd8db43d3d56e23a4a")
var taskid=566836bd8db43d3d56e23a4a;
I've tried every possible declaration of taskid to convert it so that the function could recognize the value of _id and match it:
var taskid= "ObjectId("+'"'+req.param('taskid')+'"'+")";
But till now, I am not able to match the _id with the taskid. Any fix?
if you are going to compare with ObjectId then
var ObjectId = require('mongoose').Types.ObjectId
collection.findOneAndDelete({email:email,_id:new ObjectId(taskid)},function (err, result) {
if (err) {
console.log(err);
} else {
console.log("Removed!");
console.log(result);
callback(result);
}
db.close();
});
Should work for you.
If you feel the job too hard for each and every query then you can create an new method.
String.prototype.toObjectId = function() {
var ObjectId = (require('mongoose').Types.ObjectId);
return new ObjectId(this.toString());
};
// Every String can be casted in ObjectId now
console.log('545f489dea12346454ae793b'.toObjectId());
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);
}
});
}
I am using Mongoskin + NodeJS to add new keywords to MongoDB. I want to notify the user that the entry was a duplicate but not sure how to do this.
/*
* POST to addkeyword.
*/
router.post('/addkeyword', function(req, res) {
var db = req.db;
db.collection('users').update({email:"useremail#gmail.com"}, {'$addToSet': req.body }, function(err, result) {
if (err) throw err;
if (!err) console.log('addToSet Keyword.' );
});
});
The result does not seem to be of any use since it doesn't state if the keyword was added or not.
At least in the shell you can differentiate if the document was modified or not (see nModified).
> db.test4.update({_id:2}, {$addToSet: {tags: "xyz" }})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.test4.update({_id:2}, {$addToSet: {tags: "xyz" }})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
Update for Node
When you use collection.update(criteria, update[[, options], callback]); you can retrieve the count of records that were modified.
From the node docs
callback is the callback to be run after the records are updated. Has
two parameters, the first is an error object (if error occured), the
second is the count of records that were modified.
Another Update
It seems at least in version 1.4.3 the native Mongo Node driver is not behaving as documented. It is possible to work around using the bulk API (introduced in Mongo 2.6):
var col = db.collection('test');
// Initialize the Ordered Batch
var batch = col.initializeOrderedBulkOp();
batch.find({a: 2}).upsert().updateOne({"$addToSet": {"tags": "newTag"}});
// Execute the operations
batch.execute(function(err, result) {
if (err) throw err;
console.log("nUpserted: ", result.nUpserted);
console.log("nInserted: ", result.nInserted);
console.log("nModified: ", result.nModified); // <- will tell if a value was added or not
db.close();
});
You could use db.users.findAndModify({email:"useremail#gmail.com"},[],{'$addToSet': { bodies: req.body }},{'new':false}). Pay attention to new:false switcher, it allows you to get document before update and you could check whether array contained item before update. However, it could be problematic approach if your documents are big, because you analyze it on client side.
P.S. Your original query with $addToSet is wrong: field name is missing.
Edit: I tried to use count returned by update, but it returns 1 for me in all cases. Here is the code I used for test with MongoDB 2.6:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/mtest', function(err, db) {
if(err) throw err;
db.collection('test').insert({_id:1,bodies:["test"]},function(err,item){
db.collection('test').update({_id:1},{$addToSet:{bodies:"test"}}, function(err,affected){
if(err) throw err;
console.log(affected); //1 in console
});
});
});
i am update a array from Collection with this JSON:
{
"<arrayname>":"<value>"
}
route.js
routes.post("/api/:id", Controller.addOne);
Controller.js
async addOne(req, res) {
//juryman id to list add
if (Object.keys(req.body).length === 1) {
console.log("Size 1");
}
await Session.findOneAndUpdate(
{ _id: req.params.id },
{ $addToSet: req.body }
)
.then(function(success) {
res.send("Successfully saved.");
})
.catch(function(error) {
res.status(404).send(error);
});
},
I have five arrays in my Collection and this changes the JSON array name-value and updates correctly, the respectively Collection array. This works only for one item.