Node.js + Mongoose - what's going wrong? - node.js

I have been studying a node.js + mongoose simple app, however, something went wrong. I have been working based on some examples from this site, but no lucky at all.
The code runs, however, no records are being returned from db(which is populated, btw). Can someone have a look and gimme some help? I am working on this for more than a day now, but with no joy.
models/entidade.js
var mongoose = require('mongoose')
,Schema = mongoose.Schema
,ObjectId = Schema.ObjectId;
var entidadeSchema = new Schema({
cnpj: String,
razaoSocial: String,
nomeFantasia: String,
endereco: String,
unidades: [{ codigo: String, nome: String, endereco: String, ativo: {type: Boolean, default: true} }],
dataCriacao: { type: Date, default: Date.now },
cadastroAtivo: { type: Boolean, default: false },
});
module.exports = mongoose.model('Entidade', entidadeSchema);
routes/entidades.js
var Entidade = require('../models/entidade.js');
exports.list = function(req, res) {
Entidade.find(function(err, entidades) {
console.log("route IN: %d records", entidades.length );
res.send(entidades);
});
};
and finally, server.js
var express = require('express');
var app = express();
app.configure(function () {
app.use(express.logger('dev'));
app.use(express.bodyParser());
});
// connection to mongoDB
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1/ccidev');
var entidade = require('./routes/entidades');
app.get('/entidades/list', entidade.list);
app.listen(3000);
As I said, when running the app, I don't get any errors, but an empty result. Any help is appreciated.
Thanks and regards,
Vinicius

According to the documentation, the first argument of Model.find() is the condition
Try
Entidade.find({}, function(err, entidades) {});
routes/entidades.js
var Entidade = require('../models/entidade.js');
exports.list = function(req, res) {
Entidade.find({}, function(err, entidades) {
console.log("route IN: %d records", entidades.length );
res.send(entidades);
});
};

Related

Why won't my rest api post request save my array in my mongodb database

I'm trying to learn to make an api with node.js For my backend i'm using mongodb and I'm using mongoose as ORM. I created my user model as follows.
// User.js
var mongoose = require('mongoose');
var UserInfoSchema = new mongoose.Schema({
street: String,
housenumber: String,
city: String,
postcode: String,
bus: String,
});
var UserFullSchema = new mongoose.Schema({
name: String,
email: String,
password: String,
Userinfo: [UserInfoSchema]
});
mongoose.model('User', UserFullSchema);
const User = mongoose.model('user',UserFullSchema)
module.exports = User;
My Usercontroller looks like this:
// UserController.js
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({ extended: true }));
var User = require('./User');
// CREATES A NEW USER
router.post('/', function (req, res) {
User.create({
name : req.body.name,
email : req.body.email,
password : req.body.password,
Userinfo: [{
street : req.body.street,
housenumber : req.housenumber,
city : req.body.city,
postcode : req.body.postcode,
bus : req.body.bus,
}]
},
function (err, user) {
if (err) return res.status(500).send("There was a problem adding the information to the database.");
res.status(200).send(user);
});
});
For some reason when I call my API using postman to test I can never seen to be able populate my array. Did I do something wrong?
Picture as example:
Page I checked before posting:
Page I checked
You definition where you want to have a cross reference by the _id seems off.
Userinfo: [UserInfoSchema]
should probably be:
Userinfo: [{ type: mongoose.Schema.Types.ObjectId, ref: 'UserInfoSchema' }]
This way you would have a cross reference by _id. Btw not a fan of those names. It reads very confusing. I assume these are just for testing.
Now, from a simple express kinda perspective Are you even referencing the values from req.body?
Shouldn't the values be req.body.Userinfo.street?
Userinfo: [{
street : req.body.Userinfo.street, //
housenumber : req.body.Userinfo.housenumber,
city : req.body.Userinfo.city,
postcode : req.body.Userinfo.postcode,
bus : req.body.Userinfo.bus,
}]
On a side note, you can send Full fledged JSON using postman, go to the raw tab and select application/json from the dropdown
I dont know what the problem was but I was able to resolve the issue by splitting my models in 2 different files.
I made a new file called Userinfo like this:
// Userinfo.js
var mongoose = require('mongoose');
var UserInfoSchema = new mongoose.Schema({
street: String,
housenumber: String,
city: String,
postcode: String,
bus: String,
});
module.exports = UserInfoSchema;
There I exported my whole Schema
And called that Schema in my User model file like this:
// User.js
var Userinfo = require('../userinfo/Userinfo.js');
var mongoose = require('mongoose');
var UserFullSchema = new mongoose.Schema({
name: String,
email: String,
password: String,
Userinfo: [Userinfo]
});
const User = mongoose.model('user',UserFullSchema)
module.exports = User;
And my controller looked like this:
// UserController.js
var express = require('express');
var mongoose = require('mongoose');
var router = express.Router();
var bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({ extended: true }));
var User = require('./User');
router.post('/', function (req, res) {
User.create({
name : req.body.name,
email : req.body.email,
password : req.body.password,
Userinfo: [{
street : req.body.Userinfo.street,
housenumber : req.body.Userinfo.housenumber,
city : req.body.Userinfo.city,
postcode : req.body.Userinfo.postcode,
bus : req.body.Userinfo.bus,
}]
},
function (err, user) {
if (err) return res.status(500).send("There was a problem adding the information to the database.");
res.status(200).send(user);
console.log(req);
});
});
After that I used postman as before and voila issue resolved:

Mongoose pre-save hook fires, but does not persist data

I am encountering a problem where my Mongoose pre.save() hook is firing, but the attribute does not get saved to the database. I have been searching for a long time without finding an answer.I found this thread, and the behaviour I am experiencing is very similiar, but OP's problem is related to the context of this, whereas I seem to have a different problem.
Here is my models.js:
'use strict';
const mongoose = require("mongoose");
const slugify = require("slugify");
let Schema = mongoose.Schema;
let BlogPostSchema = new Schema({
title: {
type: String,
required: true
},
createdAt: {type: Date, default: Date.now},
updatedAt: {type: Date, default: Date.now},
author: String,
post: {
type: String,
required: true
}
});
BlogPostSchema.pre('save', function(next) {
this.slug = slugify(this.title);
console.log(this.slug);
next();
});
// Passed to templates to generate url with slug.
BlogPostSchema.virtual("url").get(function() {
console.log(this.slug);
console.log(this.id);
return this.slug + "/" + this.id;
});
BlogPostSchema.set("toObject", {getters: true});
let BlogPost = mongoose.model("BlogPost", BlogPostSchema);
module.exports.BlogPost = BlogPost;
And here is the relevant lines in the router file index.js:
const express = require('express');
const router = express.Router();
const BlogPost = require("../models").BlogPost;
// Route for accepting new blog post
router.post("/new-blog-post", (req, res, next) => {
let blogPost = new BlogPost(req.body);
blogPost.save((err, blogPost) => {
if(err) return next(err);
res.status(201);
res.json(blogPost);
});
});
I am able to save the blog post to the database, and my console.log's correctly prints out the slug to the console. However, the this.slug in the pre-save hook does not get persisted in the database.
Can anybody see what the problem is here? Thank you so much in advance.
Mongoose will act according to the schema you defined.
Currently, your schema does not contain s filed named slug.
You should add a slug field to your schema.
Changing your current schema to something like this should work:
let BlogPostSchema = new Schema({
slug: String,
title: {
type: String,
required: true
},
createdAt: {type: Date, default: Date.now},
updatedAt: {type: Date, default: Date.now},
author: String,
post: {
type: String,
required: true
}
});

While creating api with nodejs, reference error: schema is not defined

I want to reach information with get method on Postman. But whenever i "localhost:3000/api/mekanlar/mekan's objectid", i get reference error "Mekan is not defined". Here is my mekansema.js file in /app_api/models.
var mongoose = require('mongoose');
var saatSema = new mongoose.Schema({
gunler: {type: String, required: true},
acilis: String,
kapanis: String,
kapali: {type: Boolean, required: true}
});
var yorumSema = new mongoose.Schema({
ad: String,
puan: {type: Number, required: true, min:0, max:5},
yorumMetni: String,
saat: {type: Date, default: Date.now}
});
var mekanSema = new mongoose.Schema({
ad: {type: String, required: true},
adres: String,
puan: {type: Number, default:0, min:0, max:5},
imkanlar: [String],
mesafe: {type: [Number], index:'2dsphere'},
saat: [saatSema],
yorumlar: [yorumSema]
});
mongoose.model('Mekan', mekanSema, 'Mekanlar');
and mekanlar.js file in /app_api/controllers
var mongoose = require('mongoose');
var mekan = mongoose.model('Mekan');
var jsonCevapYolla = function(res, status, content){
res.status(status);
res.json(content);
};
module.exports.mekanGetir = function(req, res){
if (req.params && req.params.mekanid){
Mekan
.findById(req.params.mekanid)
.exec(function(hata, mekan){
if(!mekan){
jsonCevapYolla(res, 404, {
"mesaj" : "mekanid bulunamadı."
});
return;
}
else if(hata){
jsonCevapYolla(res, 404, hata);
return;
}
jsonCevapYolla(res, 200, mekan);
});
}
else{
jsonCevapYolla(res, 404, {
"mesaj" : "istekte mekanid yok"
});
}
};
and this is index.js in /app_api/routes.
var express = require('express');
var router = express.Router();
var ctrlMekanlar = require('../controllers/mekanlar');
var ctrlYorumlar = require('../controllers/yorumlar');
//Mekan Rotaları
//router.get('/mekanlar', ctrlMekanlar.mekanlariListele);
//router.post('/mekanlar', ctrlMekanlar.mekanEkle);
router.get('/mekanlar/:mekanid', ctrlMekanlar.mekanGetir);
//router.put('/mekanlar/:mekanid', ctrlMekanlar.mekanGuncelle);
//router.delete('/mekanlar/:mekanid', ctrlMekanlar.mekanSil);
//Yorum Rotaları
//router.post('/mekanlar/:mekanid/yorumlar', ctrlYorumlar.yorumEkle);
//router.get('/mekanlar/:mekanid/yorumlar/:yorumid', ctrlYorumlar.yorumGetir);
//router.put('/mekanlar/:mekanid/yorumlar/:yorumid', ctrlYorumlar.yorumGuncelle);
//router.delete('/mekanlar/:mekanid/yorumlar/:yorumid', ctrlYorumlar.yorumSil);
module.exports = router;
it's difficult to see where the problem is, since you don't provide a stack trace. but I think at this line:
Mekan
.findById(req.params.mekanid)
Mekan should be mekan.

Nodejs include Models

Im having problems to make my server.js use my models.
I do have other models with same structure, like for example:
var Post = mongoose.model('Post');
var Comment = mongoose.model('Comment');
but they works fine.. somehow.
But if If i try to use:
var Crime = mongoose.model('Crime');
i get:
throw new mongoose.Error.MissingSchemaError(name);
^
MissingSchemaError: Schema hasn't been registered for model "Crime".
if i switch to:
var Crime = require('./models/Crime');
or
var Crime = require('./models/Crime.js');
i get the response:
Cannot find module './models/Crime'
Crime model code:
var mongoose = require('mongoose');
var CrimeSchema = new mongoose.Schema({
username: {type: String, lowercase: true, unique: true},
time: String,
salt: String
});
CrimeSchema.methods.performCrime = function(pass) {
/*var deferred = $q.defer();
deferred.notify('loading....');
deferred.reject('Greeting is not allowed.');
return deferred.promise;
*/
return 22;
};
mongoose.model('Crime', CrimeSchema);
EDIT
example of working model:
var Post = mongoose.model('Post');
and post.js model
var mongoose = require('mongoose');
var PostSchema = new mongoose.Schema({
title: String,
link: String,
upvotes: {type: Number, default: 0},
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
});
PostSchema.methods.upvote = function(cb) {
this.upvotes += 1;
this.save(cb);
};
PostSchema.methods.downvote = function (cb) {
this.upvotes -= 1;
this.save(cb);
};
mongoose.model('Post', PostSchema);
You forgot to export the module at the end.
var Crime = mongoose.model('Crime', CrimeSchema);
module.exports = Crime;

Mongoose add the object without the values on mongoDB

I have this JS code, it`s a server that will have CRUD functions
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var options = {
db: { native_parser: true },
server: { poolSize: 5 }
};
mongoose.connect('mongodb://localhost/agenda', options);
var Schema = mongoose.Schema;
var contatoSchema = new Schema({
nome: String,
telefones: [],
createdOn: {type: Date, default: Date.now}
});
var Contato = mongoose.model("Contato", contatoSchema);
app.use(bodyParser.json());
app.use(express.static('public'));
app.post('/adicionar', function(req, res){
var contato = req.body;
contato = new Contato({nome: contato.nome, telefones: contato.telefones});
contato.save(function(err, data){
if (err) console.log(err);
else res.json(data);
});
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
when i try to add an object using the URL '/adicionar' on Postman:
{
"nome": Vinicius,
"telefones": [
123456
]
}
he gives me this answer
{
"__v": 0,
"_id": "57439973e033c9902174cad0",
"createdOn": "2016-05-23T23:59:47.284Z",
"telefones": []
}
the problem is that the function doesn`t pass the correct values on the fields 'nome' and 'telefone', but he creates the array 'telefones' on mongoDB, i have the database 'agenda' created too, and he also creates the collection 'contato'.
i tried to rewrite the code search for syntax errors, i think that the bodyParser or Express mondule isn`t working but i installed both on the folder.
Other note, when i change the values of nome: contato.nome, telefones: contato.telefones to nome: "vinicius", telefones: [1235312], and run the code as node application he creates the object in the mongo DB with these values.
you need request as Json
{
"nome": "Vinicius",
"telefones": [
123456
]
}
try define your Schema like this
var contatoSchema = new Schema({
nome: String,
telefones: [Number],
createdOn: {type: Date, default: Date.now}
});
i was trying to pass the json object as a Text in postman
http://imgur.com/w5hYkgw
now the code is working, sorry for that

Resources