Having problems after getting random document in MongoDB - node.js

function randomSpam(){
MongoClient.connect(uri, function(err, db) {
if (err) throw err;
const dbo = db.db("database0");
dbo.collection("spams").aggregate([{ $sample: { size:1, } }]).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
}
Console output
As you can see above I managed to get a random document, now my question is : How can I access a field of the random document I have got? Thanks. (in this case the field named "link, check console output)

result[0].link
is what you want — the 0 refers to the first document, and the link refers to the field.

You can try, it should work:
result[0].link

Related

native js how to find a field name of a collection where another field equal to certain value

I know that on robomongo if I want to find _id of user where username = test2 I can use
db.getCollection('user').find({},{_id:1},{"username":"test2"})
now, on visual studio code, I want to find value of field "disabled" from user collection where field "username" value equal to variable "tempusername" value. I tried:
colUser = mongoDb.collection("user");
var status = colUser.find({},
{ disabled:1},{ username:tempusername},function (err, doc) {
console.log(doc);
});
but it shows value of status is "undefined". What is the write code for this?
I think it's something you're looking for.
const url = 'mongodb://localhost:27017'
MongoClient.connect(url, (err, db) => {
const dbo = db.db('mydb')
dbo.collection('user').find({disabled:'1',username:tempusername}).toArray((err, doc) => {
if(err){
console.log(err)
}
console.log(doc)
db.close()
})
})
I found the answer, basically the way it work is the result will be return inside the function, so I have to put it like this:
var statusbuffer;
colUser.findOne({ username:tempusername},{ _id:0,disabled:1},function (err, userstatus){
// User result only available inside of this function!
if (err) {
next("Failed to update records");
} else {
console.log("disabled status here:",userstatus.disabled) // => yields your user results
statusbuffer = userstatus.disabled;
next();
}
});
thanks all for your comments!

Show entire MongoDB contents in Node.js API

First off, don't worry, it's a tiny data set - I realise it wouldn't be wise to dump an entire production DB to a single screen via an API... I just need to get a JSON dump of entire (small) DB to return via an API endpoint in a Node.js application.
My application does successfully return single records with this code:
MongoClient.connect("mongodb://localhost:27017/search", function (err, db) {
if(err) throw err;
db.collection('results', function(err, collection) {
// search for match that "begins with" searchterm
collection.findOne({'string':new RegExp('^' + searchterm, 'i')}, function(err, items){
// get result
var result;
if (items == null || items.result == null){
result = "";
}
else {
result = items.result;
}
// return result
res.send(result);
});
});
});
So I know Node is talking to Mongo successfully, but how can I tweak this query/code to basically return what you get when you execute the following on the MongoDB command line:
$ db.results.find()
This is snippet.
model.find({}).exec(function (err, result) {
if (err) {console.error(err); return;}
else return result;
});
First use your predefined model and call find. the logic is to place a empty object {} essentially rendering . select all from this model.
Make sense?
Exactly as you've described it.
collection.find({}).exec((err, result) => {
if (err) {
console.log(err);
return;
}
if (result.length > 0) {
// We check that the length is > 0 because using .find() will always
// return an array, even an empty one. So just checking if it exists
// will yield a false positive
res.send(result);
// Could also just use `return result;`
});
Thanks guys, I appreciate your answers pointing me in the right direction, in terms of using {} as the query. Here is the code that eventually worked for me:
db.collection('results', function(err, collection) {
collection.find({}).toArray(function(err, docs) {
res.send(docs);
});
});
The crucial element being the toArray(...) part.

mongodb in nodejs return undefined when trying to connect to collection

when I write this code below I get:
Connected correctly to DB
undefined
undefined
I have collection named users, so this sould not happened... why is the happening?
Thanks
var url = 'mongodb://user:pass#ds023475.mlab.com:23475/small-talkz';
MongoClient.connect(url, function(err, db) {
if (err) {
console.log(err);
return db.close();
}
console.log("Connected correctly to DB.");
// update a record in the collection
console.log(db.collection("users"));
console.log(db.users);
return db.close();
});
I would say you need to .find() what it is you want from the collection. However, it is strange that it returns undefined. Try this code:
var MongoClient = require('mongodb').MongoClient, format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if(err) throw err;
db.collectionNames(function(err, collections){
console.log(collections);
});
});
to see what collection names the current database has. Perhaps it doesn't exist?
Otherwise, try finding the collection elements, as shown in the docs example.

MongoError : selector must be a valid JavaScript object

I am using mongodb driver for nodejs.
I am getting below error while updating a record.
{"name":"MongoError","message":"selector must be a valid JavaScript
object","driver":true}
Here is my script :
MongoClient.connect(url, function (err, db) {
if (err)
{
console.log('Unable to connect to the mongoDB server. Error:', err);
return;
}
var collName = "bank";
var SelectParas = {"name":"ABC"};
var UpdateValues = {"name":"PQR"};
db.collection(collName).update(collName,SelectParas,{$set:UpdateValues},function (err,numUpdated){
if(err)
{
console.log('err');
console.log(err);
return;
}
if(numUpdated)
{
console.log('Updated Successfully %d document(s).', numUpdated);
}
db.close();
});
});
I can write the below line in mongo console & it works.
db.bank.update({"name":"ABC"},{$set:{"name":"PQR"}})
You are passing collecion name i.e. a string as find query of the update. Need not pass collecton name there.
db.collection(collName).update(collName,SelectParas,{$set:UpdateValues},function (err,numUpdated)
// collName need not pass in the update function.
Need to use
db.collection(collName).update(SelectParas,{$set:UpdateValues},function (err,numUpdated) instead.

Mongoose removes too many from ID

I may be misunderstanding something, but on the client I have a request sent to the server. Something like:
$.post("/resources/remove", {"id": 52024e25b26d39f931000003})
On the server I have
Resource.remove({_id: request.body.id})
The "ID" is correct and using Resource.find with the same arguments returns the record I want to remove. However, when this is run it removes all Resource records. The return value of exec(function (err, returnValue) is the number of Resource records that were there, so it is definitely removing all of them. Using Remove.(request.body.id) does the same thing.
Do I need to do anything else to make sure that only the record with the corresponding _id is removed? If the entry is invalid why is it removing all records?
Try using Resource.findOneAndRemove Reference
I've never used that but this is what I use and it works perfectly for me
PostModel.findOne({_id: id}, function (err, result) {
if (err) {
throw err;
}
if (result) {
PostModel.remove({_id: id}, function (err, result) {
if (err) {
throw err;
}
res.json(200, result);
});
}
});

Resources