CloudantDB: using db.get without id - node.js

I have a table:
id: 001
name: test
provider_id:ABC123
and I try to query with provider_id and get a error message, but not with id:001
db.get("ABC123", function(err, data) {
// The rest of your code goes here. For example:
console.log("Found id:", data);
});
Please give me your thoughts how to run successfully db.get + provider_id

You can't use db.get without the ID. However you can use either Query or Views to find the document you are looking for.
With query you can use a selector such as {"provider_id":"ABC123"} to find the documents which contain that provider id.
With views you can use the provider_id as the key and the doc id or null as the value, such as:
function (doc) {
emit(doc.provider_id, doc._id);
}
If you are using null as the value, you should use the include_docs=true option for the request. See your library's documentation on how to use views and query.

Related

Not able to access the data inside of an object

I am fetching id column value from database for a particular email. In this case I am passing email and want to get primary key i.e id. This operation is successful as I get object which contains Object with the right and expected result. However I am not able to access the object.
I am receiving object like this:
[ UserInfo { id: 21 } ]
And I am not able to access id part of it.
I am using node.js, postgres for database and typeorm library to connect with database.
const id = await userRepo.find({
select:["id"],
where: {
email:email
}
});
console.log(id)
This prints the above object.
The id I am getting is right. But I am not able to retrieve the id part of the object. I tried various ways for e.g.
id['UserInfo'].id, id.UserInfo.
Please help me in accessing the object I am receiving
Typeorm .find() returns an array of objects containing entries corresponding to your filters, in your case, all entries with an email field corresponding to the email you specified.
Because the result is an array, you can access it this way:
const records = await userRepo.find({
select: ['id'],
where: {
email,
},
})
console.log(records[0].id)
You could also use the .findOne() method, which returns a single element and might be a better solution in your case :)
When you are putting a field in the select part select:["id"], you are only retrieving this part of the database.
It is like your query was this: select id from userRepo where email = email
and you need to put * in the select part to retrieve all the information:
const id = await userRepo.find({
select:["*"],
where: {
email:email
}
});

Express, Mongoose, db.findOne always returns same document

I am attempting a CRUD app with MEAN stack. I am using mongoose in Express to call to the MongoDB. I am using the FindOne function with a specified parameter, and it's always returning the same (incorrect) document.
I know I am connected to the correct database, since I get a document back from that collection, but it's always the same document, no matter what I pass as the parameter.
module.exports = mongoose.model('Player', playersSchema, 'players'); //in player.js
const Player = require('./model/players');
app.get('/api/player/:id', (req, res) =>{
Player.findOne({id: req.params.playerId},
function(err, player) {
if(err) {
res.json(err);
}
else {
res.json(player);
}
});
});
I have 3 separate "players", with three distinct "playerID" fields (38187361, 35167321, 95821442). I can use Postman to GET the following URL, for example:
http://localhost:3000/api/player/anythingyouWantInHere
and it will return 38187361, the first document. I've been over this website, many tutorials, and the Mongoose documentation and I can't see what I'm doing wrong..
I'd like to eventually find by playerId OR username OR email, but one hurdle at a time...
From the mongoose documentation of findOne, if you pass Id a null or an empty value, it will query db.players.findOne({}) internally which will return first document of the collection everytime you fetch. So make sure you are passing non-empty id here.
Note: conditions is optional, and if conditions is null or undefined,
mongoose will send an empty findOne command to MongoDB, which will
return an arbitrary document. If you're querying by _id, use
findById() instead.
Your route is '/api/player/:id', so the key on the req.params object will be 'id' not 'playerId'.
I don't know what/where/if you're populating the playerId param, but if you update your query to call req.params.id it should actually change the document based on the path as you seem to be wanting to do.
I had the same problem, and it was that the name of column's table was different from the model I had created.
In my model the name of the wrong column was "role" and in my table it was "rol".

Find in MongoDB

Am trying to perform Login operation by checking the username and password are correct but the problem is if i check with find operation it just returns me the ID alone i want it to return the whole field for an instance if it is a match it should return me all the details of that particular user ex: username,email,password,DOB all the details. But my query returns only id. The query is
db.users.find({"email":"cool1nn#gmail12.com"},{"pasword":"1345"})
And If i perform via Nodejs it returns the Id and Password alone
userSchema.find({"email":req.body.email},{"password":req.body.pwd},function(err,item) {
if(err) throw err;
console.log("item " + item);
})
The first argument for find() is the query, the second argument is projection.
You are doing userSchema.find(query, projection) opposed to just userSchema.find(query).
You want
userSchema.find({ email: "cool1nn#gmail12.com", pasword: "1345" })
Also since you are looking for ONE item, use findOne() not find().
userSchema.findOne({ email: "cool1nn#gmail12.com", pasword: "1345" })

Mongoose Error while performing delete

I am running into following error but I unable to completely grasp the understanding behind the error.
CastError: Cast to ObjectId failed for value "XYZ" at path "_id" for model "Partner"
I have my schema defined as following
var partnerList = new Schema (
{
partnerName: String,
supportedProducts: [String]
},
{
collection: 'partnerList'
}
);
module.exports = mongoose.model('Partner', partnerList);
The functionality of my delete function
delete: function (req, res) {
var removePartner = req.params.partnerName;
var promise = Partner.findByIdAndRemove(removePartner).exec();
promise.then(function removePartner(val) {
console.log('partner value removed');
res.send(val);
}).catch(function catchError(err){
console.error(err);
throw err;
});
}
I am trying to making a request to my node app service using
localhost:8443/data/XYZ, where i am passing the value 'XYZ' as the parameter. This value is used to delete the appropriate object from the database.
Basically the error means that whatever you pass as your "XYZ" url param is not a valid ObjectId.
Guessing from your code you use the "partner name" (probably some arbitrary string) instead of the database id of the partner. However findByIdAndRemove() requires you to specify an ObjectId as it uses this to identify which document to delete:
Model.findByIdAndRemove(id, [options], [callback])
Your delete API call could then look something like this: http://localhost:8443/data/59558ccd7acc4dd63ea88988. However for this the client needs to know the ObjectId of the partner.
So you have to either use the ObjectId of a partner in the URL, or use remove() to implement your custom delete query instead, for example like this (if name is the property you use to store your partner names):
Partner.remove({ name: partnerName }).exec();
Be careful however that this might remove multiple documents if your partner name is not unique, as remove will delete all documents matching the query.
In order to prevent this you can also use findOneAndRemove() using the same query. This would only remove one document at a time. If there are multiple partners with the same name it would remove the first one (depending on your sort order).

How to autogenerate id if there is no id in document with elasticjs v5.0

I am trying to add documents, according to elastic search documents, we can add document, even if we dont provide id... See Here
I am trying to add a document even if it doesnt have any ID. in elastic search, how can i do that?
My current code looks like this
var params = _.defaults({}, {
index: index,
type: type, //'customer'
id: data.id || null,
body: data
})
debug(params)
return this.client.create(params);
The above code gives this error
{
"error": "Unable to build a path with those params. Supply at least index, type, id"
}
Any hint would help, thanks
With the create call you MUST provide an id.
If you are not sure if an ID will be present in your data , then you can use the client.index() function instead. using that function, ES will auto-generate an ID if none is provided.

Resources