mongoose Getting a nested field value from a queried document - node.js

I am new to Node js and Mongoose and I am stuck with this one query.
exports.getIndividual=(matchId,phone)=>
new Promise((resolve,reject)=>{
var e="matchPersonal.m"+matchId+".bo1";
query={};
query[e]=1;
var quer=usersc.findOne({phone:"8989898980"}).select(query);
quer.exec(function (err, matc) {
var m=matc.toObject();
console.log('',m);
When I Run this query I get on my console this thing
{matchPersonal:{m1:{bo1:3}}}
But I just need 3 as my output and I cant use dot operator to read the object properties directly because
var b=matchPersonal.m+matchId.bo1
doesnt work as '+' cant be used here so please help

Try:
var mNum = m+matchId;
var b=matchPersonal[mNum].bo1
Because you can select properties with dot and with brackets, but brackets also can be used with variables.

Related

Mongoose find data from dynamic Collection

I am new to MongoDB & working on a MEAN application.
In the mongo database(I am using mongoose), the collections are adding dynamically from third party API like schoolList1,schoolList2,schoolList3,schoolList4,....
I am facing problem to find a solution to get data from collections, Like If a user sends the argument from FrontEnd to find data from schoolList3.
The find function should apply on that collection only & return the data.
I am unable to solve it that how should I get data without passing schema and did not get any other way.
Set collection name option for your schema from user's input:
var collectionName = 'schoolList3'; // set value from the input
var dataSchema = new Schema({/** your schema here **/}, { collection: collectionName });

forEach loop not working inside nodejs db insert?

Okay so i am trying to create a mongoose insert using 2 sets of data from two variables i have set. When i try using the loop outside the db insert function it displays the data however inside the db i get the error unexpected token .forEach.
var storedaily = store['storefronts'][3]['catalogEntries'];
var storeweekly = store['storefronts'][5]['catalogEntries'];
//console.log(storedaily);
storedaily.forEach(function(key) {
console.log(key.devName);
});
var insertstore = new Shop({
storedaily.forEach(function(key) {
itemName: key.devName
});
});
insertstore.save();
You are getting the unexpected token .forEach error because you have it placed inside the curly braces of the Shop constructor, which expects an object with keys and values.
If you want to create a Store object with a property items that is an array, you could try doing something like this:
var insertstore = new Shop({
items: storedaily.map(key => key.devName)
});

Converting string to ObjectId is failing in mongoose 4.6.0

I am trying to convert a string to ObjectId using
var body={};
var objId="57b40595866fdab90268321e";
body.id=mongoose.Types.ObjectId(objId);
myModel.collection.insert(body,function(err,data){
//causing err;
});
the above code is working fine when mongoose 4.4.16 is used, but if i update my mongoose to latest version(4.6.0) then problem occurs.
Err
object [
{
"_bsontype":"ObjectID",
"id:{"0":87,"1":180,"2":5,"3":235,"4":134,"5":111,"6":218,"7":185,"8":2,"9":104,"10":50,"11":111}
}
]
is not a valid ObjectId
The right way to insert new document is-
var newDocument = new myModel({
_id: mongoose.Types.ObjectId("57b40595866fdab90268321e")
});
newDocument.save();
In you case-
It stops working because the differences between versions of mongoose and mongo native drivers.
although, you are able to perform this by the example above, or, if you still want to use insert, you can use the myModel.insertMany (by passing object instead of array)
look here
http://mongoosejs.com/docs/api.html#model_Model.insertMany
I don't have the time to spike it, but if I remember correctly id is a simple string and _id is the ObjectId, i.e. either
body.id="57b40595866fdab90268321e"
or
body._id=mongoose.Types.ObjectId("57b40595866fdab90268321e");
That said, does it have to be that specific id? If not, you can use new myModel() and an id will be automatically created.

findOne not returning correct result( Mongo DB and nodejs)

I have stored a document in collection and when i am trying to retrieve it via findOne, it is returning me wrong result:
My Mongoose model is like:
var db = require('../db');
var mongoose = db.mongoose_var;
var companySchema = mongoose.Schema({
companyName:String
});
module.exports = mongoose.model('Company',companySchema);
Which then i am using in my server.js as :
var CompanySchema = require('./schemas/companySchema');
and when I am trying to find already inserted record as following:
CompanySchema.findOne({'Company.companyName':jsonObj.companyName},function(err,companyName){
console.log('companyName foudn:'+companyName);
if(companyName !== null){
res.status(404).json({status:'Name already in the DB'});
return;
}else{...
Its unable to find this record, but its returning probably the first record.
Folloing record is present in thedb:
When I am trying to add another company and using this findOne to check if this name already exists, findOne returns this record only. My log snippets
whereas mongo shell returns proper result only.
In mongo shell, I am using " " around field and values, not in findOne Api.
Thanks in Advance
You should probably use the following :
CompanySchema.findOne({'companyName':jsonObj.companyName},function(err,companyDocument){
if(err) console.log(err);
console.log('company found:' + companyDocument);
if(companyDocument){
res.status(404).json({status:'Name already in the DB'});
return;
}else{...
The mistake in your code was that you were using Company.companyName instead of companyName. companyName is the name of the field in the Company collection.
Hope this helps you.

mongoose: how to get string representation of query

I implementing module who automatically generate mongoose query by requested params, so for simplified test process I need to be able to get text representation of final query. How could I do that?
Like we have something like this:
var q = AppModel.find({id:777}).sort({date:-1})
I need to get something like this
"db.appmodels.where({id:777}).sort({date: -1})"
You can set debug for mongoose, which would by default send the queries to console, to use the following:
mongoose.set('debug', function (collectionName, method, query, doc) {
// Here query is what you are looking for.
// so whatever you want to do with the query
// would be done in here
})
Given a query object q you can rebuild the query using its fields, namely q._conditions and q._update. This is undocumented though and could easily break between versions of Mongoose (tested on Mongoose 4.0.4).

Resources