I'm writing an Node.js REST API using express web server and mongoDB as DB server.
The project's directory tree is the following :
https://i.stack.imgur.com/LFWGt.png
When I try to access "/new/test" route, I'm getting the error "Cannot GET /new/test". By accessing this path it should create an new entry into the DB based on "firstname" URL parameter.
Routes.js :
'use strict';
module.exports = function(app) {
var americaine = require('../controllers/americaineController');
// Firstname Routes
app.route('/new/:firstname')
.post(americaine.new_firstname);
};
DB entry creation function is located on Controller.js :
'use strict';
var mongoose = require('mongoose'),
Firstname = mongoose.model('Firstname');
exports.new_firstname = function(req, res) {
var new_firstname = Firstname(req.params.firstname);
new_firstname.save(function(err, firstname) {
if (err)
res.send(err);
res.json(firstname);
});
};
Model.js :
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var FirstNameSchema = new Schema({
/*id: {
type: Number,
required: false
},*/
name: {
type: String,
required: true
}
});
module.exports = mongoose.model('Firstname', FirstNameSchema);
Do you guys have any ideas about my issue ? Thanks in advance.
Jérémy
change the method .post() to .get()
since you're actually doing a get request and not a post request.
Related
I want to store a data in two different database in node.I tired but its not working.
// connect two databases
mongoose.connect(
keys.mongoURI
);
mongoose.connect(
keys.mongoURI1 //connectivity link
);
const express = require('express');
const app = express();
const ServerPortRouter = express.Router();
const ServerPort = require('../models/ServerPort');
ServerPortRouter.route('/add').post(function (req, res) {
const serverport = new ServerPort(req.body);
serverport.save()
.then(serverport => {
res.json('Server added successfully');
})
});
Data stored in single database, But I dont know to store this same data in two diffrent database
I am beginning to node I tired but I can't do this . Any help?
Try Creating separate models for each connection/database as below:
var conn = mongoose.createConnection('mongodb://localhost/testA');
var conn2 = mongoose.createConnection('mongodb://localhost/testB');
// stored in 'testA' database
var ModelA = conn.model('Model', new mongoose.Schema({
title : { type : String, default : 'model in testA database' }
}));
// stored in 'testB' database
var ModelB = conn2.model('Model', new mongoose.Schema({
title : { type : String, default : 'model in testB database' }
}));
I am trying to insert a sub document into all existing documents in a collection in db,in nodejs using express framework.Following is the code snippet:
updatedoc: function(update,options,cb)
{
return this.update({},update,options).exec(cb);
}
where parameters update and options are as follows :
const update = { $push: { "defaultads": content }};
const options = { multi: true};
It seems to run and gives the following output on the console :
{ n: 1, nmodified: 1, ok: 1 }
but no push takes place at all ,in any of the documents of the database.
I have checked :
1) whether i am pushing in the right db.
2) whether correct values are being passed
However I am not able to find where I am going wrong.
I am new to nodejs and would really appreciate guidance in solving this problem.
Thanks in advance.
I am giving a simple code with full fledged requirement of yours. First create a config.js using this file you will be connected to mongodb.Here is the code
module.exports = {
'secretKey': '12345-67890-09876-54321',
'mongoUrl' : 'mongodb://localhost:27017/product'
}
Next create a models folder . Keep this schema in this models folder . I named it as product.js. Here is the code
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var imageSchema = new Schema({
imagepath:{
type:String
}
});
var nameSchema = new mongoose.Schema({
productName:{type: String},
productPrice:{type: Number},
imagePaths:[imageSchema]
});
module.exports = mongoose.model("product", nameSchema);
Next create a routes folder and keep this routes code in this folder I named it as route.js. Here is the code
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var Product = require('../models/product');
var app = express();
var Router = express.Router();
Router.use(bodyParser.json());
Router.get('/product',function(req,res){
Product.find({}, function (err, product) {
if (err) throw err;
res.json(product);
});
})
Router.post('/productData',function(req, res, next){
Product.create(req.body, function (err, product) {
if (err) throw err;
console.log('Product Data created!');
var id = product._id;
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('Added the product data with id: ' + id);
});
})
Router.post('/subdocument',function (req, res, next) {
Product.find({},function (err, result) {
if (err) throw err;
for(var i=0;i<result.length;i++){
result[i].imagePaths.push(req.body);
result[i].save(function (err, ans) {
if (err) throw err;
console.log('SubDocument created!');
});
}
res.send("Successfully added");
});
})
module.exports = Router;
Next server code I named it as app.js. Here is the code
var express = require('express');
var bodyParser = require('body-parser');
var Product = require('./models/product');
var mongoose = require('mongoose');
var config = require('./config');
mongoose.connect(config.mongoUrl);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log("Connected correctly to server");
});
var app = express();
var route=require('./routes/route');
app.use('/route',route);
app.listen(3000,function(){
console.log("Server listening on 3000");
});
Run the server as node app.js.
API's
Use GET method http://localhost:3000/route/product .This is for getting all the product information.
Use POST method http://localhost:3000/route/productData .This for creating document. Post data in json format through request body like
{
"productName" : "sweets",
"productPrice" : "33"
}
You will see the response like this.
First post some documents i.e., post 2 or 3 documents and then you can see the documents with get API as I mentioned above. Then you will see all the documents contains empty sub document. You will see the response like this
And now add the sub document to all using the below api.
Use POST method http://localhost:3000/route/subdocument . Using this you can add a sub document to all the documents like this you need to add sub document
{
"imagepath" : "desktop"
}
You can see the response like this
After this again when you run the get API you can see all the sub documents are added to all documents.
Hope this helps.
I am using angularjs where i have created a js file(loginCtrl.js) and i have inclused a controller.
I have defined my db connection and schema in another file(server.js) and i want to include that file in my js.
My loginCtrl.js looks like:
test.controller('loginCtrl', function($scope, loginService){
$scope.login = function(user)
{
console.log('inside function 1');
var user = require('./server.js')
console.log('inside function');
loginService.login(user);
}
});
and my server.js files looks like:
var express = require('express');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/userregistration');
var userSchema = {
username: String,
firstname:String,
lastname: String,
email: String,
password: String
}
var User = mongoose.model('User', userSchema, 'user');
When i run the code, it gives the error like:
ReferenceError: require is not defined
It is printing the console.log defined above.
require() is a NodeJS function, your angular controller will be executed in the browser, which doesn't have that built-in function. If you want to replicate that behavior client-side, you should look at RequireJS
This is my first time writing a MVC app in Node/Express/Mongoose so I could really use some help. My .find() command just doesn't find anything! :(
Structure is that I have a an /app folder in the root. /app folder contains /models (schemas), /controllers and /views in it. And I have app.js outside in the root.
Somewhere in app.js:
// all necessary config/setup stuff..
var mongoose = require('mongoose');
mongoose.connect(config.db);
var app = express();
require('./config/routes')(app)
In my routes.js file:
var skills = require('../app/controllers/skills');
app.get('/', skills.showall);
My controller skills.js contains:
var Skill = require('../models/skill');
exports.showall = function(req, res) {
Skill.find({}, function(err, docs){
if (!err) {
res.render('index', {title: 'Skilldom', skills: docs});
}
else {
throw err;
}
});
}
Finally my Model skill.js contains:
var mongoose = require('mongoose');
//Skill schema definition
var skillSchema = new mongoose.Schema({
name: String,
length: String,
});
var Skill = mongoose.model('Skill', skillSchema);
module.exports = Skill;
My index view renders, so I see the content from my index.jade template, but for some reason the find command in the model is not fetching anything. I can confirm that my database (in MongoHQ) has real data.
Any thoughts?
Change your Skill.js for this
var mongoose = require('mongoose');
mongoose.set('debug', true);
//Skill schema definition
var skillSchema = new mongoose.Schema({
name: String,
length: String,
});
var Skill = mongoose.model('Skill', skillSchema);
module.exports = Skill;
After that, you can see at the console if mongoose is doing your queries.
I was in the same situation as you describe and it turns out I didn't understand the magic of mongoose collection naming, in your code it will try to load the "skills" and if that's not what it's named in your mongo nothing will be returned. Should really toss a "so such collection" error instead imho.
This below method gives an alternate name for your collection
var skillSchema = new mongoose.Schema({
name: String,
length: String,
},{collection : 'Skill'});
or
var Skill = mongoose.model('Skill', skillSchema,''Skill);
I'm trying to add in my first plugin - mongoose-text-search.
https://npmjs.org/package/mongoose-text-search
I'm getting the error: How to Error: text search not enabled that I can't figure out.
I have my schema in seperate file where it gets compiled into a model that I export. (Works fine.)
blogSchema.js
var mongoose = require('mongoose');
var textSearch = require('mongoose-text-search');
var blogSchema = new mongoose.Schema({
title: String,
author: String,
}],
});
// give our schema text search capabilities
blogSchema.plugin(textSearch);
var Blog = mongoose.model('Blog', blogSchema);
exports.Blog = Blog;
This is relevant code for the server side. When the client sends a request to /search/,
the socket hangs up - Got error: socket hang up and on the server side I get the
How to Error: text search not enabled message.
server.js
var express = require('express')
, mongoose = require('mongoose')
, textSearch = require('mongoose-text-search');
var search_options = {
project: 'title -_id'
};
app.get('/search', function (req, res) {
console.log("inside text search");
Reading.textSearch('writing', search_options, function (err, output) {
if (err) throw err;
console.log(output);
});
});
Thanks.
You need to enable text search on the MongoDB server as described here as it's disabled by default.