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

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');

Related

Firebase query undefined when using react-firebase-hooks

I was following Fireship's building chat app video (this part is around 3:30-4 minutes) but I am trying do something different, just using it for oauth and database setup help. I made a simple database on it, then tried to follow the query format where the collection grab and query seem to work fine since I can console.log them. But when I try to use the collection data, it is undefined. I also found another post on here similar that queried it differently and tried to use an grab a specific variable, but doing that just left me with an error saying "query2 is not a function". So below I added 2 versions of what I tested. ListItem is the collection name, and checked is one of my variables in the document.
function GrabData(){
const dataRef = firestore.collection('ListItem')
console.log(dataRef)
const query = dataRef.orderBy('createdAt')
console.log(query)
const [items1] = useCollectionData(firestore.collection("ListItem"))
console.log(items1)
const [items2] = useCollectionData(query, {idField: 'checked'})
console.log("items = " + items2)
UPADTE: From the error message it seems I needed to add permissions. However, instead of undefined it simply returns empty arrays. And I querying it incorrectly or missing something?
function GrabData(){
const dataRef = firestore.collection('ListItem')
console.log(dataRef)
const query = dataRef.orderBy('createdAt')
console.log(query)
const [items] = useCollectionData(query, {idField: 'checked'})
console.log(items)
const [values, loading, error, snapshot] = useCollectionData(query, {idField: 'checked'});
console.log(values)
console.log(snapshot)
UPDATE 2: I changed the if false to if true in the firebase edit rules tab
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
To fix the problem I had, edit the firestore permissions from "allow read, write: if false;" change the false to true. Also, make sure that you don't define a variable with the name query since you need to import the query function from firebase/firestore. Otherwise it will be overwritten and throw an error

Not able to fetch data from database while giving input to mongoose query through a href tag in Node js

This is my Schema
const AutomationSchema=new mongoose.Schema(
{EventName:String,
EventDate:String,
EventLocation:String,
EventDetails:String
}
)
events model
const EventsModel=new mongoose.model("Events",AutomationSchema)
This is my express route
Although it is getting the right route param value in variable "eventName" and the record of "eventName" also exists in database but it is returning me a "null" in the findOne query ,But when I tried to put a string like {EventName:"Sports"} e.g then it fetches the record correctly, Iam not able to figure out where did i do something wrong??
app.get("/events/:EventName",function(req,res)
{ var eventName=req.params.EventName
EventsModel.findOne({EventName:eventName},function(err,data)
{
console.log(data)
}
)})
There is a chance for this to happen if there is whitespace on any side of the event name. Try removing the whitespace using the trim method before passing it to the query
var eventName=req.params.EventName.trim()
May be your get request path is wrong.
try this /events/myEventName [do not put ':' before 'myEventName']

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.

Mongodb mapReduce: query another database

I'm trying to write a mapReduce function for MongoDb, and have a problem trying to query data from a second MongoDb database within the reduce function. Heres an example of the code:
var reduceUsers = function(key, values) {
var reducedUser = {
uid: key,
count: 0,
extractBytes: 0
};
var secondDb = db.getSiblingDB("second");
....
}
When I try running the mapReduce I get the following error:
015-09-04T15:50:23.690+0100 E QUERY Error: map reduce failed:{
"errmsg" : "exception: ReferenceError: db is not defined\n
All the code is in a .js file and I run it thus:
> mongo mapReduceTest.js
MapReduce can not access global shell objects like db. A MapReduce job can only obtain data from the one collection it runs on. It can not be used to aggregate data from more than one collection (good try, but MongoDB simply does not do JOINs). Whatever you are trying to do: it won't work this way.
When you would like advise how to solve the actual problem which lead you to this solution attempt, please open a new question which explains in detail what you are trying to do.

Finding saved data from mongo shell (no output)

Here is the code for initialization
mongoose.connect('mongodb://localhost/gpsdb');
var db = mongoose.connection;
db.on('open', function () {
// now we can start talking
});
After successful opening, I am saving data like this, it's giving me no errors.
function saveGPSData(data){
var newData = new GPSData(data);
newData.save(function(err){
if(err)
return console.error(err);
});
}
Now in mongo shell, I am trying to retrieve that data but it's giving me empty output.
> use gpsdb
> db.GPSData.find();
>
It's giving me no output. Also can I found what models are there in gpsdb?
Here is the full source code http://pastebin.com/K7QPYAx8
JUST FOUND THAT in db folder there these files for my db created by mongodb
/data/db/gpsdb.0
/data/db/gpsdb.1
/data/db/gpsdb.n
A good place to start to get a quick answer is
https://groups.google.com/forum/#!forum/mongoose-orm
the community is very responsive :)
In the shell I did the following
>use gpsdb
switched to gpsdb
>db show collections
gpsdatas
From here I found that collection name is gpsdatas...... Not sure why its adding extra (s) to my modal, although you can see from the code that I am setting Modal to
var GPSData = mongoose.model('GPSData', GPSDataSchema);
Now using the shell its working like this
>db.gpsdatas.find()

Categories