findOne() doesn't work - is something wrong with my syntax? - javascript

Db creation:
var mongojs = require('mongojs');
var db = mongojs('rodrigo-contatos', ['rodrigo-contatos']);
i'm trying to do a search in database with this code, using findOne from mongojs, that is the code:
app.get('/detalhesContato/:id', function(req, res){
var id = req.params.id;
console.log(id);
db.contatos.findOne({_id: mongojs.ObjectId(id)}, function(err, doc) {
console.log(err);
res.json(doc);
});
console.log(id) the id is correct but findOne is not working no matter what i do ;(.
"567a16ba28dee028f4a8ad78 <-- console log from id
TypeError: Cannot read property 'findOne' of undefined at
/Users/Michel/Documents/AngularProjects/RodrigoBranasListaTelefonica/server.js:48:12"

With mongojs, you need to explicitly identify the collections you want to access as properties of db when you call mongojs to create your db object. So because you're trying to access the contatos collection, that name needs to be provided to your mongojs call in the second (array of strings) parameter:
var db = mongojs('rodrigo-contatos', ['contatos']);
Or you can just skip the short-cut access from db and get the collection later:
var contatos = db.collection('contatos');
contatos.findOne(...);

Ok problem solved you need to identify collection when creating db connection.
Interesting that was only necessary for findOne() with find() was working just fine this way:
var db = mongojs('rodrigo-contatos', ['rodrigo-contatos']);
but like this, work like charm with findOne():
var db = mongojs('rodrigo-contatos', ['contatos']);

Related

Can't get to query MongoDB's ObjectId using Cypress

I'm trying to execute the following query
db.getCollection('name').find({_id : ObjectId("hereGoesAnId")})
I'm using mongodb module and use cy.task to query the db each time. This is working properly. In fact if I change id for another attribute to query, it will work like a charm.
Problem is I can only identify the task by this id and the ObjectId is the one that's giving me issues.
If I try sending the query this way:
const result = await.collection.find({_id: `ObjectId(${varName})`}).toArray()
the result comes empty because it interprets ObjectId as a string and does not find anything.
However if I do it this way:
const result = await.collection.find({_id: ObjectId(`${varName}`)}).toArray()
I get an error saying "ObjectId is not defined...
I'm new to mongo and I'm not sure if there's a workaround for this?
Top of the your code add this:
const { ObjectId } = require('mongodb');

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

Mongodb does not save a document

I am trying to store some data from an HTML formulary. I send the data using the HTTP POST method and I received them using Express framework in Node.js. The data arrives and it seems to work, but when I try to store them into MongoDB using Mongoose, the database is created but no data is stored when I execute DB.sis_dictionary.find()
I've tried to build different types of schemas and models, but none seems to work. And I get no error from Node.js, it seems to be working, but the MongoDB database does not store anything.
const Mongoose = require('mongoose');
Mongoose.connect('mongodb://localhost:27017/sis_dictionary', {useNewUrlParser: true});
const Schema = Mongoose.Schema;
const wordSchema = new Schema({
word: String
})
const Word = Mongoose.model('Word', wordSchema);
app.post('/saveWord', (req, res) => {
var word = new Word({word: String(req.body)});
word.save(function(err){
if(err) {
return console.error(err);
} else {
console.log("STATUS: WORKING");
}
})
console.log(req.body);
})
server.listen(3000);
console.log("SERVER STARTUP SUCCESS");
In the console, I get the message: "STATUS: WORKING".
sis_ditionary is your DB name and Words should be your collection name. As mongoose automatically creates a plural name for collection from a model if model name not specified when creating from a schema
db.collection.find() is a command to find a collection data when using mongo-shell. Run below command to get data:
use sis_dictionary
db.Words.find()
To beautify result use pretty method
db.Words.find().pretty()
First command will select DB and second command list collection data.
So when you execute db.sis_dictionary.find() it won't work because sis_dictinary is your DB name.
Nodejs way with 'mongoose'
//Model.find({});
Word.find({});
Also, check this line var word = new Word({word: String(req.body)});
What does req.body have? If req.body is {word:"example word"} then you directly pass req.body to modal constructor ie new Word(req.body);
According to your database URL, mongodb://localhost:27017/sis_dictionary, sis_dictionary is the database name.
And according to your mongoose model, Word is your collection name.
When you save a document, it saves under a collection. So you have to make a query under the collections.
So when you try to get data using DB.sis_dictionary.find(), definitely it won't work.
Your query should be like db.collection.find()
Use the following query,
use sis_dictionary
db.words.find()
// for better view
db.words.find().pretty()
For more please check the documentation.
Thank you everybody. You were all right, it was a problem related to my collections names. db.words.find().pretty() worked perfectly!The problem is solved.

Mongoose is connected but can't find data

I have a problem and could really use some help.
We had an application that used MySQL and we are switching over to MongoDB.
We are using Node.js with Express and have MongoDB and Mongoose for the database
We have looked at the MongoDB and Mongoose documentation and searched for related questions on Stack Overflow but we seem to be missing something.
This is what we have in app.js:
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost:27017/DBName');
This is our usersModel.js
var db = require('mongoose');
var Schema = db.Schema;
var userSchema = new Schema({
u_id : Number,
u_name : { type: String, required: true },
u_lastname : String
});
module.exports = db.model('user', userSchema);
And this is what we use in the userController:
var User = require('../models/usersModel');
User.find({}, function(err, users) {
if (err) throw err;
console.log("Found users: ", users);
});
The console.log(db.connection.readyState); says it is connecting.
And the User.find() doesn't seem to give out an error, but instead gives an empty array/undefined.
We would really appreciate it if someone could tell us what we overlook.
Thanks in advance.
Not sure why anyone thought this was a good idea, but here's what mongoose does:
Mongoose by default produces a collection name by passing the model name to the utils.toCollectionName method. This method pluralizes the name.
As a bonus, it's in lower-case which sucks when you have table names with camel case convention.
You can fix it by setting below option in your scheme:
var userSchema = new Schema({..}, { collection: 'user' });
More on this here.
Your find() call looks fine to me.
Are you sure there are users in your collection? Does creating a new user throw an error that you didn't notice? Maybe you can verify that there are indeed users in your collection by popping open a terminal and writing:
> mongo
> use DBName
> show collections
> db.user.find()
And that will return all users that exist.
At: iuliu.net: We get both errors the first was [] and the second is undefined.
At JohnnyHK: Thank you for your submit, but we are sure the the user collection is in this database and the properties we search exists.
At Juuso: Thanks for your feedback your but in the mongo terminal we got the collection output.
Some one asked us a critical question if we tried this with monk. We
installed monk and we have find the database, collection and got
result back. We're still not sure what the problem with Mongoose was,
but with monk it works.
Thank you guys for your feedback and time.

Display the data onto webpage retrieved from mongodb using node.js

Heres my problem. Might be a bit trivial. I am using node.js to write a form which has radio buttons, drop down boxes. I have been able to save data and also retrieve it successfully but I am not able to write it onto web page. What is the correct way to write the data onto a page
You can do this pretty easily with express and mongoose. First you would connect to mongoDB using mongoose, and then set up some of the variables used to interact with mongoDB from mongoose (i.e. mongoose.scheme & mongoose.model), and finally you simply send your mongoDB data to a web page through express's res.render function:
mongoose.connect('mongodb://localhost/test', function(err){
if(!err){
console.log('connected to mongoDB');
} else{
throw err;
}
});
var Schema = mongoose.Schema,
ObjectID = Schema.ObjectID;
var Person = new Schema({
name : String
});
var Person = mongoose.model('Person', Person);
app.get('/', function(req, res){
Person.find({}, function(err, docs){
res.render('index', { docs: docs});
});
});
After sending the data, you can simply reference the 'docs' variable in your web page. Express automatically uses the Jade framework. In Jade you could do something like list all the names of the people in your database:
- if(docs.length)
each person in docs
p #{person.name}
- else
p No one is in your database!

Categories