MongoDB query $unset inside Cloud Function (Node JS 16) not working - node.js

I have this query running on my Firebase cloud Function :
const result = userCollection.updateOne({ _id: "user1"}, {"$unset": testField});
And it throws the error :
Unhandled error ReferenceError: testField is not defined
at /workspace/index.js:153:67
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async /workspace/node_modules/firebase-functions/lib/common/providers/https.js:438:26
I can't find sample codes anywhere to make it work.
I have also tried to do :
const result = userCollection.updateOne({ _id: "user1"}, {"$unset": "testField"});
But got a MongoDB error :
MongoServerError: Modifiers operate on fields but we found type string instead. For example: {$mod: {<field>: ...}} not {$unset: "testField"}
What is the correct syntax here please ?
Note : I make a $set query that is actually working fine :
userCollection.updateOne({ _id: "user1"}, {"$set": {testField: "test"}});

The syntax you are using for $unset is the one in aggregation.
From official doc, the correct syntax to be used in update should be
{ $unset: { <field1>: "", ... } }
Mongo Playground

Related

MongoDB & Mongoose query returns null for aggregate $or search with non-matching field, returns individual searches or with undefined value omitted

I'm a bit confused by the behavior I'm seeing in a Mongoose/MongoDB query, as it seems that the $or operator is being treated as an $and
I have the following Collection Document that I am querying for:
{
"_id": {
"$oid": "5bd0d709ff8eef5d5325090f"
},
"audienceTrackingID": "3e66c213-fe0b-4096-a99c-558a6c349b4b",
"mainframeTrackingID": null,
"partner1TrackingID": "85c5f168-08da-44d3-bbef-fbb3b8392ded",
"__v": 0,
"contentFocus": "Cooking",
"ipRange": [
"29.142.127.151"
]
}
With the following query:
console.log(req.headers['x-original-ip']) // '29.142.127.151'
console.log(req.headers['x-audience-tracking-id']) // undefined
console.log(req.headers['x-partner-1-tracking-id']) // "85c5f168-08da-44d3-bbef-fbb3b8392ded"
const clientMatch = await Client.findOne({
$or: [{
ipRange: req.headers['x-original-ip'],
audienceTrackingID: req.headers['x-audience-tracking-id'],
partner1TrackingID: req.headers['x-partner-1-tracking-id'],
}]
})
console.log(clientMatch) // null
Somewhat puzzling, as querying for individual fields, as well as removing my query where the param is undefined within the actual query (req.headers['x-audience-tracking-id']) will produce results (Which makes me wonder, why is this acting like an AND and giving me null when one queryfield fails???)
// ALL QUERIES HIT AND RETURN A MATCH:
const tryThis = await Client.findOne({partner1TrackingID: req.headers['x-partner-1-tracking-id']})
const ipMatch = await Client.findOne({ipRange: req.headers['x-original-ip']})
const clientMatch = await Client.findOne({
$or: [{
ipRange: req.headers['x-original-ip'],
partner1TrackingID: req.headers['x-partner-1-tracking-id'],
}]
})
It makes no sense to me. Why would I need to omit a field which may not match from an $or operator in order to get a hit, when other fields match?
When you try to run your query you actually get:
query failed: cannot compare to undefined
See this here
This is one reason you get no results, another is that your $or query is not correct. You need to separate the or-ed items into separate objects for MongoDB:
So change your code to this:
const clientMatch = await Client.findOne({
$or: [
{ipRange: req.headers['x-original-ip']},
{audienceTrackingID: req.headers['x-audience-tracking-id'] || ''},
{partner1TrackingID: req.headers['x-partner-1-tracking-id']},
]
})

Mongoose find does not return results mongo does

I have a method called getTeamEmployees which should get employees that have teamId equals to the method parameter teamId. It looks like this:
public getTeamEmployees(teamId: number): Promise<any> {
return MDBDatabaseController.EmployeeModel.find({ teamId: teamId }).exec();
}
I have enabled mongoose debug and in the console I can see what query mongoose execute. This is the query:
employees.find({ teamId: 13 }, { fields: {} })
If I execute this using the mongo shell I get this:
db.employees.find({ teamId: 13 }, { fields: {} })
Error: error: {
"ok" : 0,
"errmsg" : ">1 field in obj: {}",
"code" : 2,
"codeName" : "BadValue"
}
And if I execute it without the { fields: {} } part everything is ok. It gives me 5 results.
I'm using mongoose with typescript and my model is instantiated like this:
MDBDatabaseController.EmployeeModel = model<IEmployee>('Employee', EmployeeSchema.schema);
Where IEmployee is an interface that extends mongoose.Document and has a field called teamId that is of type Number capital N.
EmployeeSchema is a class that has a static property called 'schema' that is equal to a new instance of mongoose.Schema which has a property called teamId of type Number.
What could be the problem ?
The problem was that I was doing something wrong in the resolve function of the promise. I was doing something like
res.status(200).send({})
. So no matter what query was executed all that I was getting back on the client side was {}.

MongoDB does not search for documents

but I cant find any items after ID,
Calendar.model inside is doc:
/* 1 */
{
"_id" : ObjectId("5a3425b58399c6c26cf1c848"),
"doctorID" : ObjectId("5a31392cc99fe923c0810096"),
"doctor" : "Bartłomiej Flis",
"calendar" : []
}
And in nodeJS API I am trying to find the doc using function:
router.get('/list-of-dates', (req, res)=> {
Calendar.find({ doctorID : req.query.doctorID})
.then((Calendar)=>{
console.log(Calendar)
res.send(Calendar)
})
.catch((err)=>{
console.log(err)
})
});
the value of req.query.doctorID is string -> 5a31392cc99fe923c0810096
Anyone can tell me why this function can't find any item? I think it is the fault that in the database variable doctorID is as ObjectId and in the API req.query.doctorID is a string, how to improve it in the API to work.
First, import in the beginning of the file the following:
const ObjectID = require('mongodb').ObjectId;
Then, change your search query to (i.e. wrap it into the ObjectId() function)
{ doctorID: ObjectId( req.query.doctorID ) }
What is the difference? MongoDB stores keys in ObjectId type, whereas you are trying to find something with type String. You were correct. That's why you do not get anything.
Let me know if that helps.

findarray in mongodb and output to array in nodejs

I have an array inside a collection in mongodb as per below.
{
"_id" : ObjectId("53dbb05fa976627439d43884"),
"employee" : [
{
"date" : "1986-03-10"
},
{
"date" : "1986-12-11"
}
]
}
Now I want to find all distinct date and output it to array in nodejs format.
var collection = db.collection('employee');
collection.distinct('employee.date').toArray(function(err, docsa) {
console.log(docsa);
});
};
The problem is I will receive the following error, but those collection.distinct command can be run on mongodb.Anyhow I can avoid the error ?
TypeError: Cannot call method 'toArray' of undefined
Or is there any way I can use collection.find() to get the same output?
you try collection.distinct('employee.data'), on a collection called 'employee'. I believe you want :
collection.distinct('date')

MongoDB group query works in terminal, throws error in nodejs file

I've got a query that works fine in the terminal querying my mongodb collection, however inside of the function that I want to group the data, I'm getting the following error:
// QUERY WORKS:
/*
> db.twitterhashtags.group({ key: {"text":true}, initial: {sum:0}, reduce: function(doc, prev) {prev.sum +=1}});
[
{
"text" : "spnyc",
"sum" : 1
},
{
*/
//RUNNING QUERY CAUSES THIS ERROR:
// TypeError: undefined is not a function
// at Collection.group.scope (/Users/propstm/Projects/nodeproject/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/collection.js:1341:16)
//at g (events.js:185:14)
This is the line of code that throws the error shown above.
db.collection("twitterhashtags").group({ key: {"text":true}, initial: {sum:0}, reduce: function(doc, prev) {prev.sum +=1}});
the driver is not following the console convention 100%. The docs have examples of using group.
http://mongodb.github.com/node-mongodb-native/api-generated/collection.html#group
However if it's a new app and you are using 2.2 you should not use group unless you have to and use the aggregation framework instead.
http://docs.mongodb.org/manual/aggregation/

Resources