I am running following query
var query = breeze.EntityQuery
.from('employees').inlineCount(true).then(function(data) {
console.log(data.inlineCount); //undefined
});
This is the data returned by server (written in python, a non-EF server).
{ "inlineCount" : 100, "results" : <result_object> }
I am also using jsonResultsAdapter.
extractResults: function (data) {
var results = data.results;
if (!results) throw new Error("Unable to resolve 'results' property");
return results;
},
Any idea what I am doing wrong here? Will it not work with non-EF source?
Related
I'm trying to use find() but in function system.js in mongo db but when i run the script the result is
this is my findstored() function
db.system.js.save({
_id:"findstored",
value:function(){
var data = db.counters.find({}, (err, data) => {
data.forEach((data) => {
print("Customer Name: "+data.first_name)
})
return data.first_name;
})
}
})
I just want to display the result with function in system.js. Thank you
Not sure what is the purpose of your function, but this is the right syntax for that function to be saved in system.js:
db.system.js.save({
_id:"findstored",
value:function(){
var ret = "Not found";
db.counters.find().forEach(function(data){
print("Customer Name: "+data.first_name)
ret = data.first_name;
})
return ret;
}
})
And make sure you run db.loadServerScripts(); after saving the function to have it properly loaded.
Do not store application logic in the database. There are performance limitations to running JavaScript inside of MongoDB.
db.system.js.save({
_id:"findUserInformation",
value:function(x){
return db.users.findOne({ "_id" : x }, { firstName:1 }, (err, data) => {
return data
})
}
})
On other shell or command use this findUserInformation function like this
db.loadServerScripts();
findUserInformation("5d7b4ef6f691b71b5097e9cb");
In your question please check return type and run query first and then return data.
In findstored function Application code also is typically most effective when it shares version control with the application itself.
I have changed the object structure from
{
id:"...",
name:"...",
url:"...",
studentAccess:{
"A":"....",
"B":"...",
},
ecosystemId:"..."
}
TO:
{
id:"...",
name:"...",
url:"...",
studentAccess:[
{
"X":"....",
"Y":"..."
},
{
"X":"....",
"Y":"..."
},
{
"X":"....",
"Y":"..."
},
],
ecosystemId:"..."
}
in API we get list of these objects based on ecosystemid or student access item "X", name or any field..calling like this in API
var acc = await _eco.FindByUser();
var query = await _db.CourseDocuments.FindAsync(w => w.EcosystemId == acc.Identifier);
after query executes i get this error pls help me i need to change structure anywhere after it changed in mongoDB?
I'm working on MEAN stack to create some web services.
I thought of using ES6 for synchronizing mongodb find operations.
Here is the code(UserService):
var Todo = require('../models/user.js');
var db = mongoose.createConnection('mongodb://localhost:27017/abc');
var Users = db.model('User');
function *myGenerator() {
return yield Todo.find({});//Throwing Undefined function Todo.find
//return yield Users.find({}); //DOes not returns documents but returns a json object which has full mongodb database details
}
function getDocs(){
var iterator = myGenerator();
var firstYield = iterator.next();
}
return yield Todo.find({}) is throwing exception Undefined function Todo.find
return yield Users.find({}); does not return documents but returns a JSON object which has full mongodb database details
return yield Users.find({}).exec() returns following output
{ value:
Promise {
emitter:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined },
emitted: {},
ended: false },
done: false }
PS: I used --harmony node js option as well.
Could you please help me to get User rows/documents?
Todo.find({}); returns a Query object. You must call exec function on that object to execute the query. e.g.
Todo.find({}).exec(function (error, docs) {
if (error) {
// handle
}
if (docs) {
// yeah !!!
}
})
Also mongoose database connection is asynchronous. So any queries made before the connection is established obviously wont work. Here's a working example..
var mongoose = require('mongoose');
mongoose.Promise = Promise;
var db = mongoose.connect('mongodb://localhost:27017/test', (error) => {
if (error) {
throw error
}
console.log('DB Connected');
var Todo = require('./models/user.js');
var Users = db.model('User');
function *myGenerator() {
yield Todo.find({}); // Returns a Query object
//yield Users.find({}); // Returns a Query object
}
function getDocs(){
var iterator = myGenerator();
var firstYield = iterator.next();
// firstYield is a `Query` object
firstYield.value.exec((error, users) => {
if (error) {
throw error;
}
console.log(users);
})
}
getDocs();
});
var Todo = requires('models/user.js'); produces ReferenceError: requires is not defined
should be var Todo = require('models/user.js');
maybe even
var Todo = require('./models/user.js'); because 'models/user.js' is relative to the node_modules directory
return yield Todo.find({});
should be yield Todo.find({});
As far as I can see this code will throw an Exception.
Please provide the actual code and some more info like what version of node.js you are currently running ?
p.S I wrote this in the answers section because I have yet to earned the comment everywhere priveledge
I am a beginner with Node.js and Mongoose. I spent an entire day trying to resolve an issue by scouring through SO, but I just could not find the right solution. Basically, I am using the retrieved values from one collection to query another. In order to do this, I am iterating through a loop of the previously retrieved results.
With the iteration, I am able to populate the results that I need. Unfortunately, the area where I am having an issue is that the response is being sent back before the required information is gathered in the array. I understand that this can be handled by callbacks/promises. I tried numerous ways, but I just haven't been successful with my attempts. I am now trying to make use of the Q library to facilitate the callbacks. I'd really appreciate some insight. Here's a snippet of the portion where I'm currently stuck:
var length = Object.keys(purchasesArray).length;
var jsonArray = [];
var getProductDetails = function () {
var deferred = Q.defer();
for (var i = 0; i < length; i++) {
var property = Object.keys(purchasesArray)[i];
if (purchasesArray.hasOwnProperty(property)) {
var productID = property;
var productQuery = Product.find({asin:
productQuery.exec(function (err, productList) {
jsonArray.push({"productName": productList[0].productName,
"quantity": purchasesArray[productID]});
});
}
}
return deferred.promise;
};
getProductDetails().then(function sendResponse() {
console.log(jsonArray);
response = {
"message": "The action was successful",
"products": jsonArray
};
res.send(response);
return;
}).fail(function (err) {
console.log(err);
})
});
I am particularly able to send one of the two objects in the jsonArray array as the response is being sent after the first element.
Update
Thanks to Roamer-1888 's answer, I have been able to construct a valid JSON response without having to worry about the error of setting headers after sending a response.
Basically, in the getProductDetails() function, I am trying to retrieve product names from the Mongoose query while mapping the quantity for each of the items in purchasesArray. From the function, eventually, I would like to form the following response:
response = {
"message": "The action was successful",
"products": jsonArray
};
where, jsonArray would be in the following form from getProductDetails :
jsonArray.push({
"productName": products[index].productName,
"quantity": purchasesArray[productID]
});
On the assumption that purchasesArray is the result of an earlier query, it would appear that you are trying to :
query your database once per purchasesArray item,
form an array of objects, each containing data derived from the query AND the original purchasesArray item.
If so, and with few other guesses, then the following pattern should do the job :
var getProductDetails = function() {
// map purchasesArray to an array of promises
var promises = purchasesArray.map(function(item) {
return Product.findOne({
asin: item.productID // some property of the desired item
}).exec()
.then(function product {
// Here you can freely compose an object comprising data from :
// * the synchronously derived `item` (an element of 'purchasesArray`)
// * the asynchronously derived `product` (from database).
// `item` is still available thanks to "closure".
// For example :
return {
'productName': product.name,
'quantity': item.quantity,
'unitPrice': product.unitPrice
};
})
// Here, by catching, no individual error will cause the whole response to fail.
.then(null, (err) => null);
});
return Promise.all(promises); // return a promise that settles when all `promises` are fulfilled or any one of them fails.
};
getProductDetails().then(results => {
console.log(results); // `results` is an array of the objects composed in getProductDetails(), with properties 'productName', 'quantity' etc.
res.json({
'message': "The action was successful",
'products': results
});
}).catch(err => {
console.log(err);
res.sendStatus(500); // or similar
});
Your final code will differ in detail, particularly in the composition of the composed object. Don't rely on my guesses.
Running into problems getting any data out of mongo using mongoose. The connection seems fine as i've got debugging statements that are being printed out. I've searched high and low for what could be causing this but afaik I'm setting up the schema and collections fine.
here's what i have in a file called posts.js:
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost:27017/sister', function(err) {
if (err) throw err;} //this does not get printed
);
mongoose.connection.on("open", function(){
console.log("mongodb is connected")} //this gets printed
);
var Schema = mongoose.Schema;
var thePost = new Schema({
name : String
});
mongoose.model('post', thePost);
var posts = db.model('post');
posts.find({}, [], function(err, calls) {
console.log(err, calls, calls.length); //prints out: null [] 0
});
To seed the data, I've done this in my mongo shell, which inserts a document and then shows that find all can find it:
> randumb = { name : 'emile' };
{ "name" : "emile" }
> db.post.insert(randumb);
> db.post.find({});
{ "_id" : ObjectId("4e775e8cc24f31883fdafbab"), "name" : "emile" }
try changing
var posts = db.model('post');
to
var posts = mongoose.model('post');
To keep it even shorter, try and change:
mongoose.model('post', thePost);
var posts = db.model('post');
to:
var posts = mongoose.model('post', thePost);