How to pass ObjectID as query parameter in node-red to mongodb? - node.js

I am using node-red-contrib-mongodb3 and having trouble to pass an ObjectId as an argument, not being able to use a MongoDB auto-generated _id, is there any way to use "_id": 'ObjectId("myID")' as an argument?
I have followed the module tutorial on passing query parameters node-red-contrib
Here is an example:
I have the following document in my collection:
{
"_id" : ObjectId("5c9156c7f8c3ec3259454571"),
"name" : "teste_site_1",
}
If I pass as msg.payload to findOne Operation
msg.payload = { "name" : "teste_site_1" }
returns my document without ObjectID in _id
{
"_id" : "5c9156c7f8c3ec3259454571",
"name" : "teste_site_1",
}
if I pass the _id as argument:
msg.payload = { "_id" : "5c9156c7f8c3ec3259454571" }
returns empty.
I can not call ObjectId in node-red and also cannot pass as string ObjectId.
I wonder if there is already a way to pass ObjectId as an argument.
Is this a bug or am I missing something?

I have solved by using as a parameter the return of ObjectId function in 'mongodb' node module but in order to use node modules inside a function node, one must import it to global context inside your node-red directory.
on windows:
C:\\users\username\.node-red\settings.js
in Ubuntu
~\.node-red\settings.js
and include the ObjectId as global import
functionGlobalContext: {
require: require, // Not mandatory
ObjectId : require('mongodb').ObjectID,
},
I have also included 'require' module for some may find it useful to not mess with settings.js and also make it unnecessary the process restart to add future modules.
And inside the function node, I just passed the payload as follows.
var ObjectId = global.get('ObjectId');
msg.payload={
"_id":ObjectId("5c9156c7f8c3ec3259454571")
};
return msg;

Related

Loopback Find is returning Empty

Database : Mongo 3.4+
NodeJS:v6.9.4
OS: Centos 7+
In mongo shell, following command return result,
db.processticket.find({"parentProcessID": "5978ab9f82c56ec868d0d002"})
however, following code find/findOne returns empty result
app.models.processticket.findOne({
where: {"parentProcessID": "5978ab9f82c56ec868d0d002" }
}, function(err, result) {
You can use strictObjectIDCoercion flag in model definition file. Reference
Please wrap the value of parentProcessID in ObjectId function. Since mongo saves Id values as ObjectId in your where query you need to warp the value of your parentProcessID with ObjectId function. You can find ObjectID function in native mongodb module
const ObjectID = require('mongodb').ObjectID;

Mongoose unique validation error even though unique constraint is not there

var schema = new Schema({
_id: Schema.ObjectId,
email: {type: String, required: true}
});
Previously email field was unique (with unique constraint)
Now I removed unique constraint, then also it's giving unique validation error. I have restarted mongo then also it's throwing error.
Any Idea?
When you remove the unique constraint in the schema definition, you were supposed to manually remove it from the database as well. You can do this either in mongo shell by using the dropIndex() method or in your application using the native node.js driver's dropIndex() method of the collection.
You may need to confirm this first by checking the indexes currently in the database; you will most probably find the email unique index created when you populated the collection after defining the schema in Mongoose.
You can issue the command in mongo shell, supposing you have a collection named users in your database named test:
> db.users.getIndexes()
which will show the current indexes, you may see in your console an array like the following:
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "test.users"
},
{
"v" : 1,
"unique" : true,
"key" : {
"email" : 1
},
"name" : "email_1",
"ns" : "test.users",
"background" : true,
"safe" : null
}
]
For a solution in your application code, supposing you have a Mongoose model called User that has the defined schema above, you can call the getIndexes() native node.js driver's collection method:
User.collection.getIndexes(function (err, results) {
// Handle errors
});
In mongo shell, you can then go ahead and remove the email index with the dropIndex() method :
> db.users.dropIndex("email_1")
In your application code, you can also issue the command via the Mongoose model for the collection, and call the native node.js driver's dropIndex() method of the collection:
User.collection.dropIndex("email_1", function (err, results) {
// Handle errors
});
You can also follow the below steps.
Delete users collection from database.
Save user model(Schema) file and test.

Mongoclient: how to set a value of an embedded document

Im using the MongoClient in nodejs. I want to update an specific embedded document value, but I don't know how to do that.
In the mongo shell it works like a charm With {$set{doc.doc : "test"}}
But when I'm trying to use it in exactly the same way in node, It gives me the error that the dot isn't undestandable.
I've tried it as a string, which doesn't work either.
Does somebody got a solution for this problem?
EDIT:
Json doc in the Mongodb:
{
name : test,
doc : {},
}
and I want to add the following key-value pair to the 'doc'-document
test:test
Relevant Code part (How i thought It should work)
db.collection("test").update({name:test},{$set:{doc.test:test}}, callback)
You can try setting up the update object in a variable using the array-syntax style, e.g:
var update = { $set: {} };
update["$set"]["doc"]["test"] = "test"; // -> same as update = {"$set": {"doc": {"test": "test" } } }
var query = {"name": "test"};
db.collection("test").update(query, update, callback);

PATCH method to MongoDB using Node

I want to create a PATCH method for my API but there is something I don't understand. Imagine I have the following document in my MongoDB database:
{
_id : ObjectId(1234...),
name : "bob",
age : 30
}
Now I would like to update this document but I don't know what keys my API will receive. So imagine I make a request in order to change the age but also add a last_name.
The request result would be like this:
{
_id : ObjectId(1234...),
name : "bob",
last_name : "smith",
age : 44
}
The main problem here is that I don't know the arguments I will receive.
My goal is to update the values of the existing keys and add the keys that are not in the document.
Any idea?
Thanks
You want to use the $set operator.
What this does is only updates the keys that are sent in the update query. Without $set, it will overwrite the whole object, which is obviously not what you want.
app.patch('/user/:id', function (req, res) {
var updateObject = req.body; // {last_name : "smith", age: 44}
var id = req.params.id;
db.users.update({_id : ObjectId(id)}, {$set: updateObject});
});
I'm assuming a couple things here:
You are using express.
You are using either the mongodb driver or mongojs npm module

MongoDB _id is convert to ObjectID automatically, but sometime it is not.

I am using a wrapper called mongoskin to access mongoDB. mongoskin is a simple wrapper around mongoDB javascript api.
But when I write to mongoDB, sometimes _id is converted to ObjectID, sometime is it not. The different behavior causes many problem when I have to compare _id. For example:
The following documents in company collection, "creator" is not converted to ObjectID, but item in "clients" is converted to ObjectID automatically.
> db.company.find()
{ "_id" : ObjectId("53d4b452f5b25900005cb998"), "name" : "Default Company Co.", "clients" : [ ObjectId("53d4b452f5b25900005cb999"), ObjectId("53d4b452f5b25900005cb99a") ] }
{ "_id" : ObjectId("53d4b452f5b25900005cb999"), "name" : "client company for 777 - updated", "creator" : "53d4b452f5b25900005cb998", "ssn" : "12-123-1234" }
This is the nodejs code I used to assign _id for "creator"
clientCompany.creator = req.session.user.company_id;
This is the nodejs code I used to assign _id for "clients"
var updateObj = {$addToSet: {clients:resultClient._id} };
// update creator company.clients
creatorCompany.update(updateObj, function(err, result) { ...}
When I console.log "req.session.user.company_id" and "resultClient._id", they both looks like a string type. How come one end up as ObjectID in MongoDB? If there is an auto conversion, how do I make this behavior consistent?
Thanks!
I'm guessing resultClient is the result of a query and req.session.user.company_id a string from your web application? In that case you need to create an ObjectId from the string:
clientCompany.creator = mongoskin.ObjectID(req.session.user.company_id);

Resources