I am new to MongoDb, and I have a question about the insertion of data. My Mongoose schema for 'user' collection:
var user = new mongoose.Schema({
username : {type: String},
email : {type: String,index: {unique: true}},
password : {type: String},
feed : [{
title : {type: String},
description : {type: String},
latitude : {type:Number},
longitude : {type:Number},
feedImages : [{imageUrl: {type: String}}]
}]
});
Here I inserted data to username, email and password in my first service call:
app.post('/users',function(req,res) {
var username = req.body.username;
var email = req.body.email;
var password = req.body.password;
var userData = {'username':username,'email':email,'password':password};
new db.user(userData).save(function(err,result){
if (err) {
res.json({"success": '0', "message": "Error adding data"});
}
else {
res.json({"success": '1', "message": "Data added"});
}
});
});
Then I tried to insert data to feed for the above id.
app.post('/feeds',function(req,res) {
var _id = req.body._id;
var title = req.body.title;
var description = req.body.description;
var latitude = req.body.latitude;
var longitude = req.body.longitude;
db.user.update(
{_id:_id },
{$push : {
feeds:[{
title: title,
description: description,
latitude:latitude,
longitude:longitude
}]
}
}
,function (err,result) {
console.log(err);
if (err) {
res.json({"success": '0', "message": "Error adding data"});
}
else {
res.json({"success": '1', "message": "Data added"});
}
});
});
No error is shown, but the data insertion is not happening.
Your latitude and longitude should be converted to numbers:
var latitude = Number(req.body.latitude);
var longitude = Number(req.body.longitude);
Related
Hi im using MongoDB + Mongoose and some strange magic happens in my app.
Ive defined my Schema as
var schema = mongoose.Schema({
username: {type: mongoose.Schema.ObjectId, ref: 'Profile' , required:true},
user: {type: mongoose.Schema.ObjectId, ref: 'Profile' , required:true},
message: String
});
As I save my Document the new entry has ben saved and stored. It has a message and a ref on Profile in username but the user field is missing.
Same happens if I rename it to userId :/ Registered a pre save listener : already missing in my callback before save
There is no Error and I do not know how to handle this situation. Please help. Would call the a team but I can not afford
Edit :
Full Schema
var mongoose = require('mongoose');
var schema = mongoose.Schema({
username: {type: mongoose.Schema.ObjectId, ref: 'Profile' , required:true},
user: {type: mongoose.Schema.ObjectId, ref: 'Profile' , required:true},
message: String
});
var autoPopulate = function(next) {
this.populate('user');
this.populate('username');
next();
};
var autoReduce = function(next) {
if(this.username){
this.username = this.username._id;
}
if(this.user){
this.user= this.user._id;
}
next();
};
schema.
pre('findOne', autoPopulate).
pre('find', autoPopulate).
pre('save', autoReduce);
module.exports = mongoose.model('News',schema);
Request Body
{
"message": "Hi",
"username": {
"_id": "5a736607bee0360014fb28e6",
"name": "Juventus Florin"
},
"user": {
"_id": "5a736607bee0360014fb28e6",
"name": "Juventus Florin"
}
}
Code
app.put("/api/news", function(request, response) {
response.header("Content-Type", "application/json");
var payload = request.body;
new News(payload).save(function(err) {
if(err){
response.status(500).send({"message": "This is an error!", "error":err, "payload":payload});
}else{
response.status(200).send(payload);
}
});
});
After saving there is an new entry , looks like (username is populated)
{
"message": "Hi",
"username": {
"_id": "5a736607bee0360014fb28e6",
"name": "Juventus Florin"
},
"_id":"5a736607bee0360014fb278h"
}
Solution :
On 1 to 1 references there is no need to
this.user = this.user._id;
Only on 1 to Many references. Removed the pre save listener autoReduce and it works
I'm trying to figure out what exactly is happening when i want to add a document to the mongoDB database.
When i try to add a document i'm getting this error:
{
"errors": {
"name": {
"message": "Path `name` is required.",
"name": "ValidatorError",
"properties": {
"type": "required",
"message": "Path `{PATH}` is required.",
"path": "name"
},
"kind": "required",
"path": "name"
}
},
"message": "Product validation failed",
"name": "ValidationError"
}
So i'm using Express Js and Mongoose to perform this action.
In my model: product.js
var mongoose = require('mongoose');
var productSchema = new mongoose.Schema({
name: {type: String, required: true},
category: {type: String, default: ''},
price: { type: Number, default: 0},
picture: { type: String},
quantity: {type: Number, default: 0},
status: {
type: String,
enum: ['pending', 'In Progress', 'Cancelled', 'Done'],
default: 'pending'
},
date: { type: Date, default: Date.now},
description: { type: String},
owner: {type: String}
});
var Product = mongoose.model('Product', productSchema);
module.exports = Product;
In my api routes, when i define the path for performing this action:
index.js
var express = require('express');
var router = express.Router();
var productCtrl = require('../controllers/productCtrl');
router.get('/products', productCtrl.getAllProducts);
router.get('/products/:productId', productCtrl.readProduct);
router.post('/products', productCtrl.createProduct);
router.delete('/products/:productId', productCtrl.removeProduct);
router.put('/products/:productId', productCtrl.updateProduct);
module.exports = router;
Finally, in my controller file:
productCtrl.js
var Product = require ('../models/products');
var sendJsonResponse = function(res, status, content) {
res.status(status);
res.json(content);
}
module.exports.createProduct = function (req, res){
Product
.create({
name: req.body.name,
category: req.body.category,
price: req.body.price,
picture: req.body.picture,
quantity: req.body.quantity,
status: req.body.status,
date: req.body.date,
description: req.body.description,
owner: req.body.owner
}, function createProduct(err, product){
if(err){
sendJsonResponse(res, 404, err);
return;
}
else {
sendJsonResponse(res, 201, product);
}
});
}
The behavior excepted is that i should have product document returned in json format
About my environnement, I'm using :
node.js version: 6.9.4
mongodb version: 3.4.4
express version: ~4.13.4
mongoose version: ^4.9.8
I really need help guys
The exception means that the field "name" in your model is required (you set required=true), but not provided, means you pass null or undefined to it
.create({
name: req.body.name,
req.body.name is probably undefined. Check your POST action and try console.log(req.body) to see if it is populated at all.
The exception means that the field "name" in your model is required (you set required=true), Check your req.body.name POST action.
express-validator module to perform both validation and sanitization of your data to avoid this problem. like this :
req.checkBody('name', 'Product name required').notEmpty();
var errors = req.validationErrors();
//Run the validators
var errors = req.validationErrors();
if (errors) {
//If there are errors data form invalid
res.send('');
return;
}
else {
// Data from form is valid.
}
You can try this :
productCtrl.js
var Product = require ('../models/products');
var sendJsonResponse = function(res, status, content) {
res.status(status);
res.json(content);
}
module.exports.createProduct = function (req, res){
var new_product = new Product();//instance of object (model) product
new_product.name: req.body.name,
new_product.category: req.body.category,
new_product.price: req.body.price,
new_product.picture: req.body.picture,
new_product.quantity: req.body.quantity,
new_product.status: req.body.status,
new_product.date: req.body.date,
new_product.description: req.body.description,
new_product.owner: req.body.owner
new_product.save(function(err, addprod) {//save your new product in database
if (err){
res.send(err);// error when save
}
res.send(addprod);//else return a product add
});
};
I can't save my insert
MY MODELS :
Action and Type_intervention
var mongoose = require("mongoose"),
Schema = mongoose.Schema;
var actionSchema = new Schema({
action: {
type: String,
required: true,
unique: true
},
}); //Exporter le model
module.exports = mongoose.model('Action', actionSchema);
/*-----------------------------------------*/
var mongoose = require("mongoose"),
Schema = mongoose.Schema;
var type_interventionSchema = new Schema({
type_name_intervention : {type : String},
libelle : {type : String},
Standart : {type : String},
libelle_crt : {type : String},
action : {type: Schema.ObjectId, ref: 'Action'},
});
//Exporter le model
module.exports = mongoose.model('Type_intervention',type_interventionSchema);
/*--------------------------------------*/
MY CONTROLLER:
var new_type_intervention = new Type_intervention({
type_name_intervention: req.body.type_name_intervention,
libelle: req.body.libelle,
Standart: req.body.Standart,
libelle_crt: req.body.libelle_crt,
action: req.body.action,
})
new_type_intervention.save((err, newinter) => {
if (err) {
return res.send({
message: 'Error when try to save',
'intervention': new_type_intervention,
'req.action': req.body.action,
'new_type_intervention_action': new_type_intervention.action
});
}
return res.send({
message: 'Add with succes',
'intervention': new_type_intervention
})
})
POSTMAN RUN : The error is catched (new_intervention.action not apear and there type is undefined !? )
I think this is a probleme
{ "type_name_intervention":"f",
"libelle":"f",
"Standart":"f",
"libelle_crt":"f",
"action":"test"}
//Results:
{
"message": "Error when try to save",
"intervention": {
"type_name_intervention": "f",
"libelle": "f",
"Standart": "f",
"libelle_crt": "f",
"_id": "591eb2ccd4325d0e40b2d038"
},
"req.body.action": "test",
"type of new_type_intervention_action": "undefined"
}
I found the solution :
Before save : i try to find the action_id
Action.findOne({
'action': req.body.action,
})
.exec(function (err, found_action) {
if (found_action) {
new_type_intervention.action=found_action._id; // This is GOOD practice
new_type_intervention.save();
return res.send({
'type': typeof req.body.action,
message: 'type intervention ajoutee avec succes '
})
}
})
I am new to MongoDb, and I have a question about the insertion of data. My mongoose schema for 'user' collection:
var user = new mongoose.Schema({
username : {type: String},
email : {type: String,index: {unique: true}},
password : {type: String},
feed : [{
title : {type: String},
description : {type: String},
latitude : {type:Number},
longitude : {type:Number},
feedImages : [{
imageUrl: {type: String}
}]
}]
});
I want to insert data to the feedimages and my service for that is:
app.post('/uploadFeedImage',function(req,res) {
var _id = req.body._id;
var imageUrl = req.body.imageUrl;
db.user.update(
{"feed._id":_id },
{$push : {
feedImages:{
imageUrl:imageUrl
}
}
},function (err,result) {
if (err) {
res.json({"success": '0', "message": "Error adding data"});
}
else {
res.json({"success": '1', "message": "Data added"});
}
});
});
But the data is not inserted into table and no error is shown, I don't know what is the problem.
My user table is shown below:
use $ to push in the matched element of the array. i.e. for which feed._id matches
Try this:
db.user.update(
{"feed._id":_id },
{$push : {
"feed.$.feedImages":{
imageUrl:imageUrl
}
}
},function (err,result) {
if (err) {
res.json({"success": '0', "message": "Error adding data"});
}
else {
res.json({"success": '1', "message": "Data added"});
}
});
Edit
$ is update positional operator, which helps update only the element which matches the update criteria. For more info see MongoDB $ operator Documentation.
I am new to mongoose and nodejs. Please help me to understand what is wrong in my code while saving collection. My user.js looks like below
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');
var UserSchema = new Schema ({
name: { type: String, required: true },
username:{ type:String, required: true, index:{ unique: true}},
password:{ type: String, required: true, select: false},
email:{ type: String, required: true, select: true},
mobile:{ type: String, required: true, select: true},
nativecid:{ type: Schema.Types.ObjectId, ref:'City'},
regdate:{ type: Date, default: Date.now },
did:{ type: String, required: false }
});
UserSchema.pre('save', function(next){
var user = this;
if(!user.isModified('password')) return next();
bcrypt.hash(user.password, null, null, function(err, hash){
if(err) return next(err);
user.password = hash;
next();
});
});
UserSchema.methods.comparePassword = function(password){
var user = this;
return bcrypt.compareSync(password, user.password);
};
module.exports = mongoose.model('User', UserSchema);
And my City model ie city.js looks like below
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var CitySchema = new Schema({
name: { type: String, required: true },
status: { type: Boolean, default: true },
date: { type: Date, default: Date.now }
});
module.exports = mongoose.model( 'City', CitySchema );
City is already stored in database as below
{ "_id" : ObjectId("56a4a0adb0f445561cfd4e37"), "name" : "New York", "date" : ISODate("2016-01-24T10:00:13.220Z"), "status" : 1, "__v" : 0 }
I want this ObjectId of New York should be saved in user collection while user signups. I am trying like below but not succeed.
var User = require('../models/user');
var City = require('../models/city');
api.post('/signup', function(req, res){
var user = new User({
name: req.body.name,
username: req.body.username,
password: req.body.password,
email: req.body.email,
mobile: req.body.mobile
});
City
.findOne({ name: "New York" })
.populate('_id')
.exec(function (err, city1) {
if(err){
res.send(err);
return;
}
console.log('The creator is %s', city1.name);
return user.nativecid = city1._id;
})
user.save(function(err){
if(err){
res.send(err);
return;
}
res.json({
success: true,
message: 'User created successfully!'
});
});
});
I am not understanding what is wrong. Please advice me.
Just save user in city.findOne (nested) and may be no need to populate you should use projection.
City.findOne({ name: "New York" }, {name:1}) // ID return defaulat
.exec(function (err, city1) {
if(err){
res.send(err);
return;
}
console.log('The creator is %s', city1.name);
user.nativecid = city1._id;
user.save(function(err1){
if(err1){
res.send(err1);
return;
}
res.json({
success: true,
message: 'User created successfully!'
});
});
})