Search if providing id is exist on Multiple objects under array mongodb - node.js

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.

Related

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.

limit the data returned by model.find() in mongodb

I want to limit the length of data returned by Model.find() in mongodb/mongoose
here is my code
Want to return 'Excerpt' from content.
Blog.find({},{
title: 1,
content: 1 // basically wants to return content not more than 200 character
}, function(err, data){
if (err) {
console.log(err);
}
res.render('blog/posts', {
title:'All posts',
posts: data
});
});
In other words how to return limited content from mongoDB
Update
Found solution:
Match with substring in mongodb aggregation
You just need to pass limit parameter in 3rd option
Blog.find({},{
title: 1,
content: 1 // basically wants to return content not more than 200 character
},{ limit:10 }, function(err, data){
if (err) {
// You should handle this err because res.render will send
// undefined if you don't.
console.log(err);
}
res.render('blog/posts', {
title:'All posts',
posts: data
});
});

How to access mongoose data : Nodejs

I am getting data like this:
This is the code :
User.find({ Username: user }, function(err, found_user) {
console.log('user data'+ found_user );
if(found_user.length > 0){
console.log('inside found user');
var recordings = found_user.recordings;
console.log(recordings)
for (var singleRecords in recordings){
console.log("Single record :"+singleRecords);
if(!singleRecords.isPlayed){
console.log(singleRecords.playingUrl);
twiml.play(singleRecords.playingUrl);
found_user.recordings[singleRecords].isPlayed = true;
found_user.save(function (err) {
if(err)
throw err
});
}
}
}
And this is the value of found User :
user data { Username: 'B',
__v: 2,
_id: 58ac15e4b4e1232f6f118ba3,
recordings:
[ { isPlayed: false,
playingUrl: 'http://localhost:8000/public/toplay/playing_file_1487672817599.mp3' },
{ isPlayed: false,
playingUrl: 'http://localhost:8000/public/toplay/playing_file_1487672827411.mp3' } ]
}
inside found user
in variable found_user. But it is not giving me any data inside it. Like found_user.Username gives undefined value.
I want to store that recordings array inside a variable. Any idea how to do it ?
find() returns an array of docs that match the criteria in the callback hence the line
var recordings = found_user.recordings;
will not work as it's expecting a Document not an array.
You could use findOne() method which returns a document as:
User.findOne({ Username: user }.exec(function(err, found_user) {
console.log('user data'+ found_user );
if (found_user) {
console.log('inside found user');
var recordings = found_user.recordings;
console.log(recordings);
}
});

Selecting only modified subdocument from Mongo

I have a mongoose query like this:
var query = Events.findOneAndUpdate({ '_id': event._id,'participants._id':participant._id},{'$set': {'participants.$': participant}}, {upsert:false,new: true},function(err,result){
if(err){
return res.status(500).jsonp({
error: 'Unable to update participant'
});
}
console.log(result.participants[0]);
res.jsonp(result.participants[0]);
});
and the query works properly modifying the participants subdocument inside Events collection.
The problem:
I need only the modified participant to be returned as JSON and I am not in need of the entire participants array but I am not able to achieve this since I get all the participants when I do console.log(result.participants);
How do I get only the modified subdocument after the query?
You may have to use the native JS filter() method as in the following:
Events.findOneAndUpdate(
{ '_id': event._id, 'participants._id': participant._id },
{ '$set': { 'participants.$': participant } },
{ upsert: false, new: true },
function(err, result){
if(err){
return res.status(500).jsonp({
error: 'Unable to update participant'
});
}
var modified = result.participants.filter(function(p){
return p._id === participant._id
})[0];
console.log(modified);
res.jsonp(modified);
}
);

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)
}
})
})

Resources