0

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: enter image description here

Page I checked before posting: Page I checked

3 Answers 3

0

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Changing Userinfo didn't work. Now im getting the message "There was a problem adding the information to the database." in postman. And yes the names are only for testing.
That was the first step. Next one is to review your .create and change it since you cannot add like this. You would have to first create the model for UserInfoSchema then add its _id as part of the User.create UserInfo. You are sending with your post an _id and somehow that is getting into values? IT does not work this way. Read this: mongoosejs.com/docs/populate.html
0

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

4 Comments

Tried changing as you suggested but still the same result. I also tried sending via JSON but when I did no variables were populated not even the User variables.
can you console log the req.body and check if everything is coming as expected or not?
body: { name: 'Pedro Lopes', email: '[email protected]', password: '789852123', Userinfo: { street: 'street' } }, _body: true, length: undefined, read: [Function], route: Route { path: '/', stack: [ [Object] ], methods: { post: true } } }
So the problem is not in the postman request it is somehow how Im saving users to the database
0

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: Postman

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.