find function in mongodb and literal objects - node.js

I use Mongoose on nodeJS and I have the following schema in MongoDB:
var users = new Schema({
local: {
user_uuid: String
,user_name: String
,password: String
,email: String
,connectionKey: String
}
});
And I'm exporting the schema in the following way:
module.exports.users = mongoose.model('users',users);
and this is my find statment:
var AllSchemas = require('../schemas/schemas');
...
AllSchemas.users.find({ user_uuid: doctorId},function(err,obj){
...
}
but I get that the user is not found.
If I take all the parameters out of the literal object "local" it will work
I want to know how can I find things inside a literal object.

You need to use dot notation to reach inside of embedded documents in your query:
AllSchemas.users.find({ 'local.user_uuid': doctorId }, function(err,obj) {
...
}

While referring to a sub object in the schema, you should use the dot notation inside quotes.
Please refer the following link to get the more information about the dot notation
http://docs.mongodb.org/manual/core/document/#document-dot-notation
In your case, you should use:
AllSchemas.users.find({ 'local.user_uuid': doctorId},function(err,obj){
...
}
This query will return you all the documents having user_uuid equal to doctorId.

Related

Moongoose Model.find() returns empty array when i have uppercase letter in the table name

When the table name includes a capital letter (e.g. fooBar), Moongoose Model.find() returns an empty array. If I change both the table name and the search string to be lowercase without changing anything else - it works fine.
Is this expected?
I think I have read somewhere about collection names being treated by default as lowercase inside of mongoose. I always circumvent it by using models:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const FoobarSchema = new Schema({
name: { type: String }
}, { collection: 'fooBar' });
module.exports = mongoose.model('fooBar', FoobarSchema);
The important part is what you name the collection in the Schema definition. In the export that 'fooBar' can be named whatever you want and is a means to reference the model in your code.

mongoose - field contained in string

I need to make the following query, I have a model in the db that holds a string. for example lets say that's the data:
[{ a : 'test/t' },
{ a : 'test/b' }]
Now I have the following string
var search = 'http://ttt.com/test/t'
I want to make a query which will find all the documents that 'a' property is contained inside the search variable, case insensetive.
All the exmaples I've seen talk about the opposite equation.
You can use the following query for the operation which uses the short for $where. Since this runs in Javascript, expect it to run slowly.
db.coll.find(function () {
var re = new RegExp(this.a.replace("/", "\/"))
return 'http://ttt.com/test/t'.match(re)
});

single quote added to string when building a mongo string

I am trying to build query string to find documents in mongodb.
I have a variable assigned for the value in the key:value pair.
My code looks like below
var query = {"_id":orgId[0]};
var name = "_id";
console.log(query);
db.collection('orgs')
.findOne({query}, function (err,result) {
});
The value of query looks like the below
{ _id: '"567a701be4b017"' }
Its basically adding a single quote around the string value and therefor the result from the query is null. How can i get past this ?
Thanks
Sam

Update by Id not finding document

I am attempting to perform a relatively simple update using Mongoose:
var location = locationService.getLocation(typedLat, typedLong, travelRadius);
DocumentModel.update({_id : passedInId }, { location : location }, function(err, resp){
next(err, resp);
});
In this case passedInId is the string:
"561ee6bbe4b0f25b4aead5c8"
And in the object (test data I created) the id is:
"_id": ObjectId("561ee6bbe4b0f25b4aead5c8")
When I run the above however, matched documents is 0. I assume this is because passedInId is being treated like a string, however when I type it to an ObjectId:
var queryId = ObjectId(passedInId)
The result is the same, the document doesn't match. What am I missing? This seems like it should be obvious....
Mongoose will correctly interpret a string as an ObjectId. One of the following must be the case:
That record is not in the collection. Run a query in the mongo shell to check.
Mongoose I'd looking in collection other than the one containing your test data. Remember, by default, mongo will lowercase the name under which you register your model and will add an a "s" to it.
Lastly, and your answer speaks to this, maybe your model it's just not being updated with any new information.
This behavior was because I had not yet updated the model in mongoose to include the location element. There is no error, it just doesn't match or do anything.

Mongoose - find all documents whose array property contains a given subset?

I have a (simplified) model based on the following schema:
schema = mongoose.Schema({
foo: { type: String },
bars: [{ type: String }]
});
model = mongoose.model ('model', schema);
and I want to create an API to return all documents that contain all of the 'bars' which are provided in a comma separated list. So I have:
exports.findByBars = function (req, res) {
var barsToFind = req.body.bars.split(',');
// find the matching document
};
Does Mongoose provide an API for this or is there a query param I can pass to Model#find to get this functionality? I only want a document to be returned if its bar property contains all of the values in the barsToFind array.
There are ways to structure your query to do this, the approaches are different depending on your mongodb server version. So following on from your code:
For MongoDB version 2.6 and above, use the $all operator:
model.find({
"bars": { "$all": barsToFind }
},
And though the operator does exist for previous versions, it behaves differently so you actually need to generate an $and statement to explicitly match each entry:
var andBars = [];
barsToFind.forEach(function(bar) {
andBars.push({ "bars": bar })
});
model.find({
"$and": andBars
},
Both ensure that you only match documents that contain all of the entries in the array as you have specified, it's just that the syntax available to MongoDB 2.6 is a little nicer.

Resources