Mongoose add the object without the values on mongoDB - node.js

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

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:

Filter moongose results by reference field using express

I need filter the products of a collection by category id which is a reference field.
product.js
const restful = require('node-restful')
const mongoose = restful.mongoose
const productSchema = new mongoose.Schema({
name: { type: String, required: true },
category: {type: mongoose.Schema.Types.ObjectId, ref: 'CategoryProduct'}
})
productSchema.pre('find', function () {
this.find().populate('category')
})
module.exports = restful.model('product', productSchema)
routes.js
const express = require('express')
const auth = require('./auth')
module.exports = function (server) {
const protectedApi = express.Router()
server.use('/api', protectedApi)
const Product = require('../api/product/productService')
Product.register(protectedApi, '/products')
}
If I run this on Postman, http://localhost:3003/api/products/?name__regex=/test/i, I can get all products which contains 'test' on name.
So I try get all products by a specific category doing this, http://localhost:3003/api/products/?category=5af3ac4372edc6000468d766.
But as the category is an objectID, I receive this error:
{
"message": "Cast to ObjectId failed for value \"5\" at path \"category\" for model \"SimpleProduct\"",
"name": "CastError",
"stringValue": "\"5\"",
"kind": "ObjectId",
"value": 5,
"path": "category"
}
How do I filter the products by category? I do not know how to treat this parameter correctly and pass to mongoose
Here is my CategoryProduct.js file
const restful = require('node-restful')
const mongoose = restful.mongoose
const categorySchema = new mongoose.Schema({
name: {type: String, required: 'O campo Categoria é obrigatório'},
status: {type: Number, required: true},
updated_at: {type: Date}
})
module.exports = restful.model('CategoryProduct', categorySchema)
you would have to do the following in your route:
const mongoose = require('mongoose');
router.get('/', (req, res, next) => {
const category = req.query.category; // assign the query param for use
// mongoose query now
Product.find({category: mongoose.Types.ObjectId(category)}, (err, result) => {
if (err) {console.log(err)};
if (result) {
res.json(result);
}
});
});
This is just a basic example. Since you are using node-restful you might have to adjust the code but the main idea here is that you require the mongoose module using
const mongoose = require('mongoose')
then pass your category query param to it to convert the string to objectID using:
mongoose.Types.ObjectID(YOUR_CATEGORY_PARAM_HERE)
You can do this anywhere, in the your routes.js or in your express.js, just have to have the string you want to convert :)
hope that helps :).

Mongoose update query keeps on inserting data with upsert true without updating and adding only 1 field

I am working on Facebook login in Node js with Mongoose. i am getting issues while updating data.
This is my Scheme file
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// Schema
var RegSchema = mongoose.Schema({
UserName: String,
UserEmail: String,
userprofileImage : String,
userId: String,
reg_time : {
type : Date, default: Date.now
}
}, { collection: 'user' });
// Model
module.exports = mongoose.model('UserReg', RegSchema);
and this is my main file where update and insert(if not found) is placed
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var UserReg = require('./myschema.js');
module.exports = function(userdetail, callback){
var bb;
var UserAdd = new UserReg({
"UserName": userdetail.username,
"UserEmail": userdetail.useremail,
"userId": userdetail.userId,
"userprofileImage": userdetail.userprofileImage
});
var userdetailchange = {
"UserName": userdetail.username,
"UserEmail": userdetail.useremail,
"userId": userdetail.userId,
"userprofileImage": userdetail.userprofileImage
};
// Update if found otherwise Insert
UserAdd.update({"userId":userdetail.userId },{ $set:userdetailchange, $setOnInsert:userdetailchange ,upsert:true, new: true, setDefaultsOnInsert: true}, function (err, data) {
if (err) {
callback(err);
}
callback(data);
});
};
Now it keeps on inserting user data in collection with only 1 field which is userId and also a default _id field. Please help me in updating whole data if match found or Insert whole data in Collection. Any help will be highly appreciated.
upsert, new and setDefaultsOnInsert are options, which need to be passed in a separate, third argument to update (documented here):
UserReg.update({
"userId" : userdetail.userId // query document
}, {
$set : userdetailchange, // update document
$setOnInsert : userdetailchange
}, {
upsert : true, // options
new : true,
setDefaultsOnInsert : true
}, function (err, data) {
...
});

MongoError: E11000 duplicate key error

i'm making a simple blog app using nodejs + express, i can add first post without a problem but when i try to add second post i got his error { MongoError: E11000 duplicate key error collection: restful_blog_app_v2.blogs index: username_1 dup key: { : null }
this is my schema
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var BlogSchema = new mongoose.Schema({
title: String,
image: String,
body: String,
created: {
type: Date,
default: Date.now
},
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
}
});
BlogSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("Blog", BlogSchema);
this is the user schema
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var UserSchema = new mongoose.Schema({
username: String,
password: String,
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);
this is the create new post route
app.post("/blogs", isLoggedIn, function (req, res) {
req.body.blog.body = req.sanitize(req.body.blog.body);
var title = req.body.blog.title;
var image = req.body.blog.image
var body = req.body.blog.body;
var created = req.body.blog.created;
var author = {
id: req.user._id,
username: req.user.username
}
var newPost = {
title: title,
image: image,
body: body,
created: created,
author: author
}
Blog.create(newPost, function (err, newBlog) {
if (err) {
console.log(err);
res.render("new");
} else {
console.log(newBlog);
res.redirect("/blogs");
}
});
});
I've tried to dropped the entire database using db.dropDatabase() from the mongo console but the problem still persist, not sure what to do now
This is caused by passport-local-mongoose, which, according to its fine manual, makes username a unique field by default.
You have added this plugin to BlogSchema, which seems like you initially had the user data in that schema but moved it to a separate schema (UserSchema) and forgot to remove it from the former.
Start by not using it for BlogSchema, and you also need to drop the unique index on username on the blogs collection.
Can you try deleting your Schema and again send the value? I was getting the same issues. I solved with the above idea.

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

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);
});
};

Resources