Halp with weird mongoose issue

I’m playing around with node/mongo/mongoose and have a weird issue. Things seem more or less wired up, but when I try to create a new document, the default values are used instead of the ones I supply in the body of the request.

My findById and find functions seem to work. The delete and save (the create one) don’t.

app.post('/clients', async (req, res) => {
    const client = new Client(req.body);
    try {
        await client.save();
        res.status(201).send(client);
    } catch (e) {
        res.send(400).send(e);
    }
});

Do you have an example of what you exactly send?

I would try logging req.body and see what is in there just to make sure it’s what you expect (you probably already have).

The only other thing that I am unsure of is if you can create a model with a javascript object and not a mongoose schema (index.js, line 5). I’ve always passed in a schema as the second argument to Mongoose.model() and I don’t know if it’s smart enough to use a plain object. Although it’s somehow able to find stuff,…

1 Like

Yeah, that’s also a good idea.

The docs say:

const schema = new mongoose.Schema({ name: 'string', size: 'string' });
const Tank = mongoose.model('Tank', schema);

You are just adding an object as a schema.

1 Like

gasp
It’s undefined.

I don’t understand why, though. I’m using postman, POST, the body is ‘raw’ and ‘JSON’.

This is what I wrote there:

{
    "firstName": "Daisy",
    "lastName": "Cho",
    "email":"daisy@protonmail.com",
    "phone":"6026158573",
    "isCurrentClient": "true"
}

This what I get back, which are my defaults:

{
    "firstName": "firstName",
    "lastName": "lastName",
    "email": "email@email.com",
    "phone": "55555555",
    "isCurrentClient": false,
    "_id": "5f91e993adceef3a14f50990",
    "__v": 0
}

Try moving app.use(express.json()); up to right after const app = express();

1 Like

Ah, that did it! Thank you.

1 Like

Cool, good to hear.

You might also want to check out something like morgan for some logging. Not that it would have really helped here. Again, remember to mount that middleware at the top as well.

Happy coding!

1 Like