I am working with nodejs+ express and mongodb.
I am using postman and access the API.
When I use ObjectId the server not responding anything. If i removed means working good.
I am not able to fix this issue. Please can anyone help for this.
test.js
//Post Data:
{
"list_id": "56963e4dbcd5d4ff27ced0fbd"
}
var app = require('express');
var router = app.Router();
var server = require('./../../server');
var mongoUtil = require('./../../mongoUtil');
var ObjectId = require('mongodb').ObjectID;
router.post('/share', function(req, res, next) {
var data = {
query : {}
};
console.log(req.body['list_id']);
//printed 56963e4dbcd5d4ff27ced0fbd
console.log(data.query);
//printed {}
data.query = ObjectId(req.body['list_id']);
console.log(data.query);
//Here not getting any response
// this line not printed and server no response.
//Also tried the following things. but its not working.
// data.query['_id'] = new ObjectID(req.body['list_id']);
//data.query._id = ObjectId(req.body['list_id']);
var collection = mongoUtil.list;
collection.findOne(data.query, function(err, list) {
console.log(err);
console.log(list);
if (!err && list) {
res.send("Sucess");
return;
} else {
res.send("Error");
return;
}
});
});
56963e4dbcd5d4ff27ced0fbd should be of length 24. But it is 25. Make sure it is 24. It might work.
ObjectID()
Constructor
Create a new ObjectID instance
class ObjectID()
Arguments:
id (string) – Can be a 24 byte hex string, 12 byte binary string or a Number.
Returns:
object instance of ObjectID
Caught with the same error. Seems like ObjectId from mongoDB not working.
FOllowing import fixed the issue:
import { ObjectId } from "bson"
Related
I want to render a page getting info for two different queries in CosmoDB using documentdb.
I have 2 queries:
var FirstQuery = {
query: 'SELECT * FROM FactoryData',
};
var SecondQuery = {
query: 'SELECT * FROM StoreData',
};
And have this to get the data
docDbClient.queryDocuments(collLink, FirstQuery ).toArray(function (err, results) {
value1 = results;
});
docDbClient.queryDocuments(collLink, SecondQuery ).toArray(function (err, results) {
value2 = results;
});
then i want to render the view with those results but i cant get it rendering from outise of this funcions.
res.render('view.html', {"value1" : value1 , "value2" : value2});
I know that this code will not work, but i was trying to implement promises and didn't know how to do it with documentdb-q-promises.
I already read a lot of documentation about Q promise but i dont get it.
Can someone explain to me how i can do it , I`m a beginner.
Based on your requirements,I followed the npm doc and test code on github to test following code in my local express project. Please refer to it.
var express = require('express');
var router = express.Router();
var DocumentClient = require('documentdb-q-promises').DocumentClientWrapper;
var host = 'https://***.documents.azure.com:443/'; // Add your endpoint
var masterKey = '***'; // Add the massterkey of the endpoint
var client = new DocumentClient(host, {masterKey: masterKey});
var collLink1 = 'dbs/db/colls/import';
var FirstQuery = 'select c.id,c.name from c';
var collLink2 = 'dbs/db/colls/item';
var returnArray = [];
client.queryDocuments(collLink1, FirstQuery).toArrayAsync().
then(function(response){
console.log(response.feed);
var map = {};
map['value1'] = response.feed;
returnArray.push(map);
return client.queryDocuments(collLink2, FirstQuery).toArrayAsync()
})
.then(function(response) {
console.log(response.feed);
var map = {};
map['value2'] = response.feed;
returnArray.push(map);
})
.fail(function(error) {
console.log("An error occured", error);
});
router.get('/', function(req, res, next) {
res.send(returnArray);
});
module.exports = router;
Test Result:
Hope it helps you.
This is my structure of MongoDB:
I wanna make a query that return all keys and values of 1 Document in the database. I should select the document where a key "content-transition" is "ciao".
This is my code:
var router = express.Router();
const MongoCient = require('mongodb').MongoClient;
const dbName = 'myproject';
const url = 'mongodb://localhost:27017';
router.get('/get/:id', function (req, res) {
var param = req.params.id;
var myQuery = {
"content-transition":param
};
MongoClient.connect(url, function(err, client) {
var collection = client.db(dbName).collection('documents');
var result = collection.find({myQuery});
console.log(result)
});
});
I want return in the console the document into the variable "result" in relation by input parameter.
This code is written in NodeJs with che ExpressJs library.
if myQuery is defined as { "content-transition": param },
and you're calling collection.find({myQuery}),
then what you're really doing is
collection.find({ myQuery: { "content-transition": param }});
and of course mongo has no idea what to do with that.
try removing the curly brackets around myQuery when you call collection.find().
I have a code piece to run through a list of elements in an array (mysql hosts to be precise) and the task is to iterate through each element in the array - connect to mysql using the element(hostname), run a query against it and have the results in a json.
The result for the last element is not captured in the final array, while the others are.
Below are the config array and snippet
Config :
config.mysql.list = ['host1', 'host2', 'host3' , 'host1'];
The hostname can be repeated. The count of result objects in the response should be equivalent to the number of elements in the array.
const config = require('../../config.js');
//For RESTful API
const express = require('express');
const router = express.Router();
const promise=require('bluebird');
//For MySQL connection
const mysql = require('mysql');
promise.promisifyAll(config);
promise.promisifyAll(require('mysql/lib/Connection').prototype);
promise.promisifyAll(require('mysql/lib/Pool').prototype);
//Home page venue type wise breakup
router.get('/databaseRecords',function(req,res){
// Some vars
let arrStatus =[];
// Build the connection
function getConnection(serverHost){
// Setup the MySQL connection
let connection = mysql.createConnection({
host : serverHost,
user : config.mysql.user,
password : config.mysql.password,
database : config.mysql.database
});
// <- note the second return
return connection.connectAsync().return(connection);
}
promise.each(config.mysql.list,function(serverHost) {
//Create connection
return getConnection(serverHost).then(function(conn){
// Slave status
let qry = 'SELECT * FROM tableName limit 1';
// Response ?
conn.queryAsync(qry).then(function(rows){
let strresponse = JSON.stringify(rows);
let jsonresponse = JSON.parse(strresponse);
jsonresponse[0].whichRec=serverHost;
arrStatus.push(jsonresponse[0]);
//done
conn.endAsync();
});
});
}).then(function(){
// Emit the response
res.json({'data':arrStatus});
}).catch(function(err){
let respErr = JSON.parse(err.error);
res.json({'Error':respErr});
});
});
//Export routes
module.exports = router;
A bit confused as to what I am really missing in the code snippet.
Put return in front of conn.queryAsync(qry). You need to return the promise returned from conn.queryAsync. Hope this helps.
I'm learning to use the mean stack and trying to build a url shortener. I've got a module that takes the req.params.UserUrl checks and makes sure it's a valid url then creates a random number that I want to use as the short route. I can't seem to find a way to save the random number so that I can check their next url request against it. After a google search it seemed maybe the most effecient way would be to save an object in the database with the long_url and the short_url:randomNumber. My code doesn't throw any errors but when I check my heroku database it has a new entry but only has the _id and __v that mLabs generates itself. Can someone tell me where I'm going wrong.
Route File
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var URLShortener = require(process.cwd()+'/public/Modules/urlShortener.module.js');
var ShortURL = require('../models/shortUrl.js');
router.get('/', function(req, res) {
res.render('index', { title: 'FreeCodeCamp Projects' });
});
router.get('/urlShortener', function(req, res){
res.render('freecodecamp/urlShortener', { title: 'Url Shortener Site'});
});
router.get('/urlShortener/:userUrl', function(req, res){
if(URLShortener.checkValidUrl(req.params.userUrl))
{
var UserUrl = req.params.userUrl;
var randNbr = URLShortener.assignRanNbr();
ShortURL.create(URLShortener.createUrlObj(UserUrl, randNbr), function (err, smallUrl) {
if (err) return console.log(err);
else res.json(smallUrl);
});
}
else
{
res.send('Invalid url');
}
});
router.get('/:short', function(req, res){
if(randNbr == req.params.short)
{
res.redirect(userUrl);
}
else
{
res.send('Not the correct shortcut');
}
});
module.exports = router;
Url Schema
var mongoose = require('mongoose')
var Schema = mongoose.Schema
var shortUrlSchema = new Schema({
long_id:String,
short_id:Number
}, {collection: 'shortUrl'});
module.exports = mongoose.model('shortUrl', shortUrlSchema);
urlShortener Module
'use strict'
module.exports.checkValidUrl = function(url){
var pattern = new RegExp(/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+#)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%#.\w_]*)#?(?:[\w]*))?)/);
return pattern.test(url);
}
module.exports.assignRanNbr = function(){
var randNbr = Math.floor(Math.random() * (9999 - 1 + 1)) + 1;
return randNbr;
}
module.exports.createUrlObj = function(url, num){
var urlObj = {};
urlObj.original_url = url;
urlObj.short_url = 'https://rawlejuglal-me-rawlejuglal-1.c9users.io/freecodecamp/'+num;
return urlObj;
}
Your createUrlObj method is returning an object with the properties original_url and short_url, but your shortUrlSchema properties are long_id and short_id. The property names in your create method need to match your schema. The property value types must also match your schema types (currently short_url is a string and short_id is a number). I think what you really want is for your createUrlObj method to be
module.exports.createUrlObj = function(url, num){
var urlObj = {};
urlObj.long_url = url;
urlObj.short_id = num;
return urlObj;
}
and your schema to be
var shortUrlSchema = new mongoose.Schema({
long_url: String,
short_id: Number
}, {collection: 'shortUrl'});
Additionally, your '/:short' route should have a call to the database since the randNbr and userUrl variables are not defined in that route.
router.get('/:short', function(req, res){
ShortUrl.findOne({short_id: req.params.short}, function(err, shortUrl){
if(err) res.send('Invalid Url');
res.redirect(shortUrl.long_url)
})
});
I'm trying to use a new schema in my db, but get errors while trying to instantiate it. I have two other schemas (in two different model files in the folder "models"), that works perfect, and they are shaped in the same way. What does the error message mean and what can I do different to prevent it from occur?
I don't thinks its any problem with the other code in the controller, because i've tried to instantiate another db model in the same place using the same syntax, and that works fine.
The error I get: 500 TypeError: object is not a function
at Schema.CALL_NON_FUNCTION_AS_CONSTRUCTOR (native)
Sorry for all the code below. I didn't know what I could exclude in this case.
Anyway, thanks in advance!
controller file:
module.exports = function(app, service) {
var imageModel = service.useModel('image');
app.post('/file-upload', function(req, res, next) {
// other code...
var imageAdd = new imageModel.ImgSchema();
}
}
mongodb model (models/image.js):
module.exports = function (mongoose) {
var modelObject = {};
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var ImgSchema = new Schema({
name : String,
size : Number,
type : String
});
modelObject.ImgSchema = ImgSchema;
modelObject.Images = mongoose.model('Images', ImgSchema);
return modelObject;
};
For mongodb I'm using a service file (service.js):
var environment;
var mongoose = require('mongoose');
module.exports.init = function(env, mongoose) {
environment = env;
mongoose = mongoose;
};
module.exports.useModel = function (modelName) {
var checkConnectionExists = (mongoose.connection.readyState === 1 || mongoose.connection.readyState === 2);
if(!checkConnectionExists)
mongoose.connect(environment.db.URL);
return require("./models/" + modelName)(mongoose);
};
module.exports.useModule = function (moduleName) {
return require("./modules/" + moduleName);
};
The modelObject.ImgSchema is not a constructor, however, modelObject.Images is.
var imageAdd = new imageModel.Images();
I'd probably rename Images to Image