var express = require('express');
var router = express.Router();
var Product = require('../models/products');
/* GET home page. */
router.get('/', function(req, res, next) {
var products = Product.find();
res.render('shops/index', { title: 'Express' ,Product:products});
});
module.exports = router;
i am new to nodejs and mongodb .I have 5 record in database but the code above is returning 15 records from database
here is the model implemented
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({
imagePath:{type: String,required:true},
title:{type: String,required:true},
description:{type: String,required:true},
price:{type: String,required:true},
});
module.exports = mongoose.model('Product',schema);
find is an asynchronous operation where the result is provided in a callback function. Querying for it would look like that:
Product.find({}, function(err, products) () {
res.json(products);
});
But i can't see why you are getting 15 results...
Related
I have made a database on pgAdmin 4 but values are not updated when sent through signup form on node.also npm install postgre-sql giving an error
var express = require('express');
var router = express.Router();
const { Pool,Client} = require('pg')
const connectionString='postgressql://postgres:12345##localhost:5432/postgres'
const client= new Client({
connectionString:connectionString
})
client.connect()
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/action',function(req,res){
var uname= req.query.username;
var pass= req.query.psw;
var em= req.query.email;
var DOB=req.query.dob;
var gen= req.query.gender;
client.query('INSERT INTO SIGNUP(username,email,password,DOB,gender) VALUES ("'+uname+'", "'+em+'", "'+pass+'","'+DOB+'","'+gen+'")',(err,res)=>{
console.log(err,res)
client.end()
} )
})
module.exports = router;
Looks like you might have a typo there
postgressql://postgres:12345##localhost:5432/postgres
should be postgresql://postgres:12345##localhost:5432/postgres
I'm trying to insert an object in MongoDB with Mongoose, but without success.
In './models/user,js' I have:
var mongoDatabase = require('./db'); //I've connected to localhost here
var database = mongoDatabase.getDb();
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
user: String,
adress: String,
});
userSchema.methods.testmethod = function(){
console.log('test');
}
userSchema.methods.insert = function (obj) { //this works but what is the point to use Mongoose If I do it that way
database.collection("users").insertOne(obj, function(err, res) {
if(err) throw err;
console.log("1 record inserted");
});
}
var User = mongoose.model('User', userSchema);
module.exports = User;
In './controllers/user.js'
var express = require('express');
var router = express.Router();
var User = require('../models/user');
router.post("/", function(request, response) {
var obj = new User({
user: request.body.name,
adress: request.body.adress,
});
obj.testmethod(); //works fine
obj.insert(obj); //throws an error
User.insertOne(obj, function(err, res) { //error: insertOne is not a function
if(err) throw err;
console.log("1 record inserted");
});
});
module.exports = router;
I have tried few more ways to do it, but without result. Can someone help me?
You shouldn't be using whatever mongodb object you're creating in './db' to do this work, mongoose takes care of it for you. Try simplifying down to this:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
user: String,
adress: String,
});
module.exports = mongoose.model('User', userSchema);
Then in your controller code
var express = require('express');
var router = express.Router();
var User = require('../models/user');
router.post("/", function(request, response, next) {
var user = new User({
user: request.body.name,
adress: request.body.adress,
});
user.save(function(err, u) {
if (err) return next(err);
return res.json(u);
});
});
module.exports = router;
Somewhere in your app startup code (often in app.js or similar location) you'll want to call mongoose.connect(<connection url>), normally prior to setting up routes.
Note you can also call insert() explicitly, but it's a static method on the model object, like so:
User.insert({user: 'bob', address: 'somewhere, nh'}, cb)
Given the following schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var favoriteSchema = new Schema({
dishes: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Dish'
}],
postedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
}, {
timestamps: true
});
var Favorites = mongoose.model('Favorite', favoriteSchema);
module.exports = Favorites;
and the following router
var bodyParser = require('body-parser');
var express = require('express');
var mongoose = require('mongoose');
var Favorites = require('../models/favorites');
var Verify = require('./verify');
var favoritesRouter = express.Router();
favoritesRouter.use(bodyParser.json());
favoritesRouter.route('/')
.post(Verify.verifyOrdinaryUser, function(req,res,next){
req.body.postedBy = req.decoded._doc._id;
console.log('nana ' + req.body.postedBy);
Favorites.create(req.body,function(err,fav){
if(err) throw err;
fav.dishes.push(req.body);
fav.save(function(err,fa){
if(err) throw err;
res.json(fa);
})
});
});
module.exports = favoritesRouter;
Every time i do the post requires from postman, I`m attaching the dish ID to the body of the request.
{
"_id": "577a996155d73cf02b0d516f"
}
I could not come up with a solution to insert this ID into the array, instead of re-creating the whole object with only 1 id inside the array. Am i making something wrong, or something else has to be done in order to do the logic i want?
You're going to want to query the database to find the previously saved object, append to the array, mark as modified, then save. It will look something like this:
var bodyParser = require('body-parser');
var express = require('express');
var mongoose = require('mongoose');
var Favorites = require('../models/favorites');
var Verify = require('./verify');
var favoritesRouter = express.Router();
favoritesRouter.use(bodyParser.json());
favoritesRouter.route('/')
.post(Verify.verifyOrdinaryUser, function(req,res,next){
req.body.postedBy = req.decoded._doc._id;
console.log('nana ' + req.body.postedBy);
Favorites.findById(someID, function(err, fav){
if(err) throw err;
fav.dishes.push(req.body);
fav.markModified('dishes')
fav.save(function(err,fa){
if(err) throw err;
res.json(fa);
})
});
});
You'll need to figure out how you're getting the ID in there. You could use a dynamic endpoint:
favoritesRouter.use(bodyParser.json());
favoritesRouter.route('/:id')
.post(Verify.verifyOrdinaryUser, function(req,res,next){
var someID = req.params.id
})
Or you could do a search for who posted it (.find({postedBy: req.decoded._doc._id},... instead of .findById(someID,...), or something else
I'm working on a new app and trying to get mongo set up locally for storage. My api endpoints are getting hit but as soon as I try to actually call a db operation - find or save - it doesn't respond.
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var Person = require('./data/person');
var dbConfig = require('./config');
//database: 'mongodb://localhost:27017/persondb'
var db = mongoose.createConnection(dbConfig.database);
db.on('error', function() {
console.info('Error: Could not connect to MongoDB. Did you forget to run `mongod`?');
});
if (~process.argv.indexOf('mode_dev')) {
global.mode_dev = true;
console.log('Server started in dev mode.');
}
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', router);
router.route('/persons')
.post(function(req, res) {
debugger;
var person = new Person(); // create a new instance of the Person model
person.name = req.body.name;
person.save(function(err) {
debugger;
if (err)
res.send(err);
res.json({ message: 'Person created!' });
});
})
.get(function(req, res) {
Person.find(function(err, persons) {
debugger;
if (err)
res.send(err);
res.json(persons);
});
});
Here's the schema:
data/item.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var personSchema = new Schema({
name: String,
});
module.exports = mongoose.model('Person', personSchema);
I am running mongod before getting my webserver started. As soon as I get to the .save or .find calls, no error is thrown but the callbacks are never hit.
I would connect like this:
mongoose.connect("mongodb://localhost/persondb");
var db = mongoose.connection;
maybe this will help it explains problems using mongoose.createConnection(
if you use createConnection, you need to always reference that connection variable if you include a registered model, otherwise if you use mongoose to load the model, it will never actually talk to your database.
The other solution is to simply use mongoose.connect instead of
mongoose.createConnection. Then you can just use
mongoose.model(‘MyModel’) to load the requested model without needing
to carry around that db connection variable.
I have defined a custom type and I am trying to return all entries from mongo contained in the referenced collection:
Participant.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var participantSchema= new Schema({
email: String,
});
module.exports = mongoose.model('Participant', participantSchema, 'participants')
api.js
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Participant = require('../models/Participant');
router.get('/all', function(req, res) {
var participant = mongoose.model('Participant');
//var participant = new Participant();
console.log(participant);
participant.find().execFind(function (arr,data) {
res.send(data);
});
});
module.exports = router;
But due something fishy, my model does not extend (I assume the default prototype)
participant.find(...).execFind is not a function
TypeError: participant.find(...).execFind is not a function
at /Users/bogdan/private/appName/routes/api.js:13:24
Any help is highly appreciated...
Thanks
execFind was replaced with exec back in one of the 3.x releases of Mongoose.
So you must now call exec instead of execFind.