Mongoose Schema for remote MongoDb - javascript

I have opened a connection to my remote mongodb ec2 instance but now am trying to retrieve data that is nested within a collection. The database has multiple collections (ie visitor, campaign, form, etc...) and has data already in it from another source. I am using node + express for the application.
1) Do I have to define a schema in my app to match the remote database or can I just query for the data and store it in an object?
mongoose schema creation
2) Actually retrieving the values within the visitor collection, can I just use dot notation to query within the visitor collection for visitor_id using:
db.find(visitor.visitor_id)
Here is the database connection code I am using if that helps
var uri = 'mongodb://xx.xxx.xx.x'
var mongoOptions = { db: { safe: true } };
db = mongoose.createConnection(uri, mongoOptions, function (err, res) {
if (err) {
console.log('ERROR connecting to: remote' + uri + '. ' + err);
} else {
console.log('Successfully connected to: remote' + uri);
}
});

If you're using mongoose, then yes, you need to define a schema in your app to match the database.
That notation won't work. If I understand the specific query you're trying to make (to fetch the document matching a visitor_id) then you'll need something roughly like this:
// Assuming you already have mongoose connected to the database elsewhere
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var visitorSchema = new Schema({
visitor_id: Number,
etc: etc // the rest of your schema
});
var Visitor = mongoose.model('Visitor', visitorSchema);
Visitor.findOne({ visitor_id: the_id_you_want_to_query }, function (err, doc) {
// doc contains the visitor document, if found
});
I suggest you familiarize yourself with queries with MongoDB and mongoose in particular—the docs aren't super easy to understand but cover most of the main cases.

Related

I need get amount of documents in db (mongodb) [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Difference between count() and find().count() in MongoDB
(5 answers)
Closed 4 years ago.
I need get amount of documents in db (mongodb) . I tried get this value to my var like this:
var unique = collection.find({email: email}).count();
and like this:
var unique = collection.find({email: email}).toArray();
unique = unique.length;
But when I try to see this number in console, that show me 'undefined' :/
Whats wrong?
P.S sry for my english
From the docs. It's db.collection.count. Don't use find.
Returns the count of documents that would match a find() query for the
collection or view. The db.collection.count() method does not perform
the find() operation but instead counts and returns the number of
results that match a query.
Example Usage:
const MongoClient = require('mongodb').MongoClient;
// Connection url
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'users';
// Connect using MongoClient
MongoClient.connect(url, function(err, client) {
const db = client.db(dbName);
const email = 'foo#bar.com';
const query = { email: email };
const options = {};
db.collection.count(query, options, (err, result) => {
// handle error
if (err) {
console.log(err);
}
// do something with result
console.log(result);
});
});
Here is a basic example of how count might work. I assume you are using the mongodb npm and not mongoose or other mongo wrappers like it. The way I would use this in a project is by making the connection to your mongodb its own module so that it can be reused with other queries. That way you don't have to wrap every query with a connection.
If you want to get all the docs of a collection, use:
db.collection.count
If you want to get all the docs of a collection by a field, use:
collection.find({email: email}).toArray(function (err, items) {
console.log(items.length);
})

Create a new field inside a JSON

I'm using the combo Express (Node.js) and Mongoose to make a REST API. I'm trying to make the login using a JWT token but I've got a problem. When I execute the following code
const mongoose = require('mongoose');
const User = mongoose.model('User');
// other code
_api.post('/login', function (req, res) {
const data = req.body;
// some data control
User.findOne({ username: data.username}, function(err, doc) {
if (hash(password) == doc.password) { // password check
myToken = generateToken(); // generating the token
doc.jwtToken = myToken; // including the generated token to the response
res.status(200).json(doc); // return the final JSON to client
}
}
}
the final JSON returned by the API doesn't have the field "jwtToken":"mygeneratedtoken" and this is strange. I included other times new fields inside a JSON with the same syntax and it worked. I tried to use a tmp variable to which I assigned the doc content (that is a javascript object) and then I added the jwtToken filed and return the tmp variable. But nothing.
Can someone explain me if there is something wrong with my code or if there is something that I need to know?
Documents returned by mongoose are immutable, and thus assignment to doc.jwtToken does not modify the object. You can either use the lean method to modify the query, or toObject to convert the document to a regular javascript object. Try:
var docObject = doc.toObject();
docObject.jwtToken = myToken;
res.status(200).json(docObject);

How to create URL for every MongoDB document

I'm trying to map a URL using express routes to a specific value from every document I have in the database.
For example. In the Schema company.name would return a company name.
Is there a way to set the value of company.name to a unique URL?
The only way I thought of it was creating a loop or using mongoose's .find to iterate through the database and set it to
app.get('/' + name , function (req , res ) {
res.render('company.jade');
});
However I'm not sure how to access the database collections from the routes file.
Using
const Company = require('.models/company');
Doesn't return the database so not sure what to do.
I'm not really hip on Mongoose or node.js yet. Really only need to do this one thing and the rest of the app is done in angular which I'm more familiar with.
Hopefully I made some sense here. I do have code for the app buts it's all basic code from app.js and routes.js. I can add it if it would be helpful.
You are looking for Mongoose findOne query.
const Company = require('.models/company');
app.get('/:name', function(req, res){
Company.findOne({'company.name': req.params.name}) //company.name depends upon the schema you set.
.then(function(company){
if (company)
return res.send({success: true, data: company}); //return company as an object containing the queried company document.
else
return res.send({success: false, error: 'Company not found'});
})
.catch(function(err){
if (err) res.send({success: false, error: err});
});
});

MongoDB Error: Cannot create property '_id' on string

I'm using Node.js and Express on Heroku, with the MongoDB addon.
My database connection works fine and I can successfully push some data in, but not other.
Here is the database connection:
mongodb.MongoClient.connect(mongoURI, function (err, database) {
if (err) {
console.log(err);
process.exit(1);
}
// Save database object from the callback for reuse.
db = database;
console.log("Database connection ready");
// Initialize the app.
var server = app.listen(process.env.PORT || dbport, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
});
I can successfully push my Twitter API response into the database like this:
db.collection(TWEETS_COLLECTION).insert(data);
('data' is just a JSON variable)
But when I try to push another JSON variable into the database in the same method, I get an error. Code:
var jsonHash = '{"hashtag":"","popularity":1}';
var objHash = JSON.parse(jsonHash);
objHash.hashtag = req.body.hashtag;
JSON.stringify(objHash);
collection(HASHTAG_COLLECTION).insert(jsonHash);
And the error:
TypeError: Cannot create property '_id' on string '{"hashtag":"myhash","popularity":1}'
at Collection.insertMany...
...
Any ideas what I'm doing wrong?
I don't know where you are getting the jsonHash variable from but I think you are doing unecessary JSON-handling here. You are also inserting the wrong variable, you want to insert objHash which is a valid object to insert, now you are inserting jsonHash which is just a string. JSON.stringify(objHash); is not doing anything as you are not saving the JSON returned from the function. I think you want something like this?
var objHash = {
hashtag: "",
popularity:1
};
objHash.hashtag = req.body.hashtag;
collection(HASHTAG_COLLECTION).insert(objHash);
jsonHash is still a string. May be you want to save objHash instead without JSON.stringify ?

Mongojs: findOne() doesn't work

I was trying to use findOne method. But it didn't show anything.It looks like it didn't execute. Would you like to help me solve this problem?
var mongojs = require('mongojs');
var databaseUrl = "mongodb:local:27017/mydb";
var db = mongojs(databaseUrl, ["profiles"]);
var password;
db.profiles.findOne({"userId": "liu1234"}, function(err, doc) {
if (err) throw err;
else console.log(doc);
});
The format of databaseUrl is incorrect. The mongodb driver is unable to find your database.
Try:
var databaseUrl = "mongodb://localhost:27017/mydb";
The first part, mongodb://, refers to the protocol that mongodb uses to interact with the database. The next part, localhost , is a hostname that points to your machine. :27017 refers to the default port that mongodb communicates over. And, obviously, /mydb refers to your database.
If you're using a default configuration, you don't even need to specify the protocol, the host, or the port. Mongojs assumes the defaults if you don't enter them, so you can use this instead:
var databaseUrl = "mydb";
For more information check out: https://github.com/mafintosh/mongojs

Categories

Resources