I'm trying to get specific info from a javascript object from a mongo database. My code is
tags.find({tagName: tagArgs[1]}, function (err, tag) {
if (err) {
} else {
msg.channel.send(tag.tagContent)
}
})
What I want happened is for the content of the tag to be sent, however, instead it sends nothing. If I instead did
msg.channel.send(tag)
I would get an object
{
_id: 6071ce10c7b87d58acfeac7e,
tagName: 'Test',
tagContent: 'hello world',
__v: 0
}
but trying to tap into tagContent returns nothing, what am I doing wrong?
Related
I'm trying to single fetch a value from my database.
I have a collection named: randoms
Model's Name: Random
Inside the collection, I have one object and with a name field. I want to retrieve that value of 'name' and display it in my console.
The result in the console should be: 'TestName' only.
This has been my approach:
Random.find({}, (err, randoms) => {
if(err) throw err
// console.log(randoms)
res.render('entries', console.log(randoms.name))
})
The console displays the result: undefined.
Here's the database.
If I console.log(randoms) instead of console.log(randoms.name) I get the result:
[{
_id: 5e256c819f972c268493488c,
name: 'TestName',
defination: 'Home page paragraph text',
count: 2,
__v: 0
}]
so that means the connection is alright.
db.collection.find returns a Cursor which is A pointer to the result set of a query. Clients can iterate through a cursor to retrieve results.
yourCollection.find().forEach(function(item){})
This should be simple but it is surprisingly difficult and extremely frustrating. I am trying to overwrite an 'Object' field in mongodb with a new Object that the user creates in my client webpage. I have validated that all other fields I am passing to the update operation are in fact being updated, with the exception of the javascript object. Instead of it updating with the object I am passing (While I validated is being populated with the object I am passing through), it just updates it back to {} instead of whats being passed:
{ nodes:[ { w: 120, h: 80,type: 'InHive',left: 184,top: 90,text: 'item',query: 'hey',name: 'sample',id: '7686132d-6fcf-4a3b-baa2-b1c628e0b2d6' } ], edges: [], ports: [],groups: [] }
When I attempt to update the data field outside of the meteor method, directly from the mongo console interface, it overwrites that field successfully with the javascript object. What am I doing wrong here, because I cant for the life of me figure this one out?
Server Method
'updateOneWorkflow': function(id, field, object) {
this.unblock;
if (Meteor.userId()) {
var _username = Meteor.user().username;
MYCOLLECTION.update({
_id: id
}, {
$set: {
[field]: object, //this just gets reset back to {} whenever this update method is called
"metadata.last_modified_dt": new Date(), //this gets updated
"metadata.modified_by": Meteor.userId(), //this gets updated
'metadata.modified_by_username': _username //This gets updated
}
});
} else {
throw new Meteor.Error(403, "You are not authorized to perform this function");
}
}
Client Call:
var _jsonformat = toolkit.exportData();
var currentid = Session.get('rulesRowClicked')._id;
console.log(_jsonformat);
Meteor.call('updateOneWorkflow' , currentid, 'data', _jsonformat, function(err, res){
if(err){
toastr.error('Failed to save result ' + err);
}
else{
toastr.success('Saved workflow');
}
});
I believe your problem is stemming from this line: [field]: object. I don't believe that's a proper method of dynamically accessing an object's field. Instead, try to dynamically update the field as so:
'updateOneWorkflow': function(id, field, object) {
this.unblock;
if (Meteor.userId()) {
var _username = Meteor.user().username;
var newObj = {
"metadata": {
"last_modified_dt": new Date(),
"modified_by": Meteor.userId(),
"modified_by_username": _username
}
};
newObj[field] = object;
MYCOLLECTION.update({
_id: id
}, {
$set: newObj
});
} else {
throw new Meteor.Error(403, "You are not authorized to perform this function");
}
}
The issue was crazier than I expected. If you are using Meteorjs and you are using the Aldeed Schema 2 collection framework, it seems to completely ignore updates/inserts of json objects even if you set the field type to Object, unless you set up the exact same schema as the object (including nested array objects) and attach it to your collection. Dumbest thing Ive ever seen, no idea why nothing warns you of this. I removed the schema attachment and it worked.
I am using seneca-mongo-store to save the entities into backend mongodb. Here is the code I am using to save
function addObject(object){
connectToMongo('stupidDB')
seneca.ready(function(){
var collection = seneca.make$('install')
console.log("entering object")
console.log(object)
collection.save$(object, function(err, reply){
if( err )
console.log(err)
else
console.log("Reply : " + reply)
closeConnection()
})
})
}
The result of execution of this code is
$ node mongoConnect.js
2016-08-08T12:01:25.470Z 912dfpdw7ytw/1470657685436/29552/- INFO hello Seneca/0.7.2/912dfpdw7ytw/1470657685436/29552/-
entering object
{ date: 1470657685818,
product: 'MCS',
release: '16.2.1',
'SESSION ID IN LOG FILES': { '/tmp': 'json object', '/u01/app': 'json object' },
'CRYPTOGRAPHIC NAMES CHECK': { '/tmp': 'json object', '/u01/app': 'json object' } }
Reply : $-/-/install;id=1p2kfa;{date:1470657685818,product:MCS,release:16.2.1,SESSION ID IN LOG FILES:{/tmp:json object,/u01/app:json object},
seneca database connection closed!
The object is being passed but only a part of it is being stored. Is there a length restriction on it in secena plugin? Is there a setting I can change to save large json objects? Or there is some error in my way of using it? As per mongodb specifications a document can be of 16 mb size.
trying to add to my very simple collection using
Template.home.events({
'click #send-button': function(e, t) {
e.preventDefault();
msg = {
from: Meteor.user()._id,
to: Meteor.user().penpal,
sent: new Date(),
message: $('#message').val()
};
messages.insert(msg);
console.log(messages.find().fetch());
}
})
in collections.js I have
messages = new Mongo.Collection('messages');
messages.allow({
'insert': function (userId,doc) {
return true;
}
});
message gets inserted but the console shows that it is being overwritten every time, eg it adds my new message but does not keep all old messages as well. when I try to render messages using
Template.home.helpers({
'messages': function(){
return messages.find().fetch();
}
})
and then
{{#each messages}}...{{/each}}
in html I get the messages appearing for the blink of an eye and then disapearing again.
please help! I am desperate!
Based on the Q&A, it appears you simply need to publish the collection and subscribe to it:
server:
Meteor.publish('myMessages',function(){
const me = this.userId;
if ( me ){
return messages.find({ $or: [{ from: me },{ to: me }]});
}
this.ready();
});
(in the code above the collection is being filtered to messages that are pertinent to the current user, you can define your own filters as required).
client:
Meteor.subscribe('myMessages');
router.get('/wiki/:topicname', function(req, res, next) {
var topicname = req.params.topicname;
console.log(topicname);
summary.wikitext(topicname, function(err, result) {
if (err) {
return res.send(err);
}
if (!result) {
return res.send('No article found');
}
$ = cheerio.load(result);
var db = req.db;
var collection = db.get('try1');
collection.insert({ "topicname" : topicname, "content": result }, function (err, doc){
if (err) {
// If it failed, return error
res.send("There was a problem adding the information to the database.");
}
else {
// And forward to success page
res.send("Added succesfully");
}
});
});
Using this code, I am trying to add the fetched content from Wikipedia in to the collection try1. The message "Added succesfully" is displayed. But the collection seems to be empty. The data is not inserted in the database
The data must be there, mongodb has { w: 1, j: true } write concern options by default so its only returns without an error if the document is truly inserted if there were any document to insert.
Things you should consider:
-Do NOT use insert function, its depricated use insertOne, insertMany or bulkWrite. ref.: http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#insert
-The insert methods callback has two parameters. Error if there was an error, and result. The result object has several properties with could be used for after insert result testing like: result.insertedCount will return the number of inserted documents.
So according to these in your code you only test for error but you can insert zero documents without an error.
Also its not clear to me where do you get your database name from. Is the following correct in your code? Are you sure you are connected to the database you want to use?
var db = req.db;
Also you don't have to enclose your property names with " in your insert method. The insert should look something like this:
col.insertOne({topicname : topicname, content: result}, function(err, r) {
if (err){
console.log(err);
} else {
console.log(r.insertedCount);
}
});
Start your mongod server in a correct path,i.e, same path as that of what you are using to check the contents of collection.
sudo mongod --dbpath <actual-path>