The new:true option returns me the old value in MongoDB - javascript

I'm using the following code in MongoDB v2.2 NodeJS 0.8 MongoSkin 0.5 Framework:
var db = mongo.db(admin+"#127.0.0.1:27017/database",{safe:true});
db.collection('collection').findAndModify({'code':code,'email':email},[],
{
$push:
{
'code.pub':newPub,
}
},{new:true},
function(err, result)
The new true option returns me the old value in MongoDB. Why is this happening? What is wrong?

set {w: 1} or, {safe: true} which is deprecated.

in your query you search for: "{'code':code,..." and in the update you say "$push: {code.pub...
If your "code" field contains an object (sub-document) - your query will not find anything and the update will fail
Could you please post the complete statement (with the content of the variables) and an example of the document being updated?
Cheers
Ronald

Related

Confusing error message using updateOne() function on a mongodb collection

To summarize, I have a mongodb database with a 'groupcollection' in it. One of the attributes is called 'deleted' and it has values either true or false. I want to update the value of 'deleted' for a specific document using 'groupname' as the query attribute. However, when I try the code below I receive the error "TypeError: collection.updateOne is not a function"
router.post('/deletegroup', function(req, res) {
var db = req.db;
var collection = db.get('groupcollection');
var filter = {"groupname" : req.body.groupname};
var updates = { $set: {"deleted" : true} };
collection.updateOne(filter, updates, function(err) {
if (err) {
// If it failed, return error
res.send("There was a problem deleting the group from the database.");
}
else {
// And forward to success page
res.redirect("grouplist");
}
});
});
I've read the documentation on updateOne() for Node.js from mongoDB and I can't seem to figure out the reason for the error. Also, I am still very new to javascript/nodejs/mongo so I would greatly appreciate more informative answers!
The solution I came up with was using unique IDs for each group and instead of using updateOne() just using update() and having the unique ID as the query to make sure that I don't modify groups with the same name

Express/MongoDB/EJS - Can't read object

So I Have some data in my Mongo Database, which I.find() by express and send it to my EJS view. pretty simple. But the problem is when I try to read it using <pre><%=%></pre> i get undefined. Here's the entire code:
The Data Array containing Object in MongoDB:
[{
_id: 6069820f402d01120cda8cff,
imageName: 'Dining Plate',
imagePath: './public/assets/img/6.jpg',
description: 'Wallpapers',
__v: 0
}]
Express Code where I get it and send it to EJS:
app.get('/wallpapers/:id', ((req, res) => {
const urlID = req.params.id;
Thing.find({}, function (err, result) {
if (err) {
console.log(err);
} else {
var fres = result.filter(d => d._id == urlID);
res.render('wallpaper-page',{fres});
}
});
})
)
and the EJS:
<pre><%= fres.description%> %> </pre>
And Now the BIG CONFUSION: when I replace fres.description with fres._id, It works perfectly fine. but that's it, it doesn't wanna print any other key values. I've been searching far and wide for almost a day now. But nothing helps. this is annoying me now.
PS: console.log(fres.description) is undefined and console.log(fres._id) works fine.
Why? How do I fix this?
please tell me if you need any other code.
Besides the problem with the filter method returns an array, I think you have another problem accessing data from Mongoose response.
This problem is discussed here: Mongoose return data inside _doc object. You can check out my answer with a test code to demonstrate some methods to access data from Mongoose response.
Array.filter returns an array. So, var fres = result.filter(d => d._id == urlID); the variable fres is an array with an object in it.
And if you need only the object in your EJS template, you need to pass just that.
res.render('wallpaper-page',{fres: fres[0]});
Now you can access the description key directly. But I don't understand how fres._id works, it should also be undefined.

Write an object containing an array of objects to a mongo database in Meteor

In my user collection, I have an object that contains an array of contacts.
The object definition is below.
How can this entire object, with the full array of contacts, be written to the user database in Meteor from the server, ideally in a single command?
I have spent considerable time reading the mongo docs and meteor docs, but can't get this to work.
I have also tried a large number of different commands and approaches using both the whole object and iterating through the component parts to try to achieve this, unsuccessfully. Here is an (unsuccessful) example that attempts to write the entire contacts object using $set:
Meteor.users.update({ _id: this.userId }, {$set: { 'Contacts': contacts}});
Thank you.
Object definition (this is a field within the user collection):
"Contacts" : {
"contactInfo" : [
{
"phoneMobile" : "1234567890",
"lastName" : "Johnny"
"firstName" : "Appleseed"
}
]
}
This update should absolutely work. What I suspect is happening is that you're not publishing the Contacts data back to the client because Meteor doesn't publish every key in the current user document automatically. So your update is working and saving data to mongo but you're not seeing it back on the client. You can check this by doing meteor mongo on the command line then inspecting the user document in question.
Try:
server:
Meteor.publish('me',function(){
if (this.userId) return Meteor.users.find(this.userId, { fields: { profile: 1, Contacts: 1 }});
this.ready();
});
client:
Meteor.subscribe('me');
The command above is correct. The issue is schema verification. Simple Schema was defeating the ability to write to the database while running 'in the background'. It doesn't produce an error, it just fails to produce the expected outcome.

can not get data with MysqlSubscription of numtel:mysql for meteor

I am using meteor to do full stack javascript work.And I want to use mysql instead of mongodb.I find numtel:mysql on github, which is a Reactive MySQL for Meteor.
On the server side
Meteor.publish('test', function(){
let array = liveDb.select(
'select * from tasks',
[ { table: 'tasks' } ]
);
console.log('publish test mysql')
console.log(array);
return array;
});
on the client side
let mysqlData = new MysqlSubscription('test');
console.log('subscribe mysql data at client');
console.log(mysqlData);
console.log(mysqlData.length);
console.log(mysqlData.subscriptionId);
console.log(mysqlData[0]);
console.log(mysqlData[1]);
However, I can not get data on the client.And there is a strange phenomenon.From the logs, I find data of mysqlData.However, mysqlData.length is 0, mysqlData[0] and mysqlData[1] are undefined.
Who can help me?
You might want to call mysqlData.reactive() and check if it is ready by using mysqlData.ready() first.
In case the subscription does not work (it does not update the data automatically), you should make sure that you config your MySQL server correctly following the installation instruction.
For me, I could not make it work when I used capital letter on the database name, you should check it also.

How do I use jQuery's .get() method with MongoDB

I'm a complete MongoDB beginner and I'm wondering how jQuery's .get() method works. I've been able to use .post() to add and update items in the DB, and that jQuery looked like this:
$.post(document.URL, {'answers':answer})
Now I'm trying to get information to the client side first using the following find() method, which successfully retrieves the correct information and logs it into terminal.
this.find(query, {"answers":"true", "blanks":"true"}, function(err, doc){
console.log("The correct info appears in terminal: "+doc); //{_id:52a52ee1e80e7c0000000001, answers: [ 'more', 'One', 'more' ], blanks: ['try']}
return doc;
callback();
});
Than I'm trying to send that same info to the client-side with this jquery, but it only logs the html on that page, and not the desired 2 arrays from mongo.
$.get(document.URL, {'answers':[], 'blanks':[]}, function( doc ) {
console.log( doc ); //This is all the html on my page
});
How do I .get() the 2 arrays?

Categories