1

The initial problem was solved, thanks!

Now, whenever I insert the document it comes out like this:

{

_id: "5e3b64b6655fc51454548421",
todos: [ ],
title: "title"

}

It should look like this since in the schema the "title" property is above the "todos" property.

{

_id: "5e3b64b6655fc51454548421",
title: "title",
todos: [ ]

}

JavaScript

//project schema
const schema = mongoose.Schema({
    title: String,
    todos: []
});

const Project = mongoose.model('Project', schema);

//add a project
app.post('/addProject', (req, res) => {
    const collection = db.collection('projects')
    const proj = new Project({title: req.body.title});
    collection.insertOne(proj, function(err, results) {
        if (err){
            console.log(err);
            res.send('');
            return
        }
        res.send(results.ops[0]) //retruns the new document
    })
})
Vlad Tanasie
  • 63
  • 1
  • 10

3 Answers3

2

You're renaming your key in below line:

const proj = new Project({title: req.body.projTitle});

Your schema expects projTitle, try to change it to:

const proj = new Project({projTitle: req.body.projTitle});

Mongoose schema defines the structure of your document. Whenever you try to save additional field that's not defined in your schema it will be simply ignored by mongoose.

mickl
  • 48,568
  • 9
  • 60
  • 89
  • Thank you for the answer, that was the problem. Just one more thing, now whenever I insert one in the DB, the todos array is put above the title property in the JSON object. – Vlad Tanasie Feb 06 '20 at 10:59
  • @VladTanasie it's not a good idea to rely on the order of keys in MongoDB: https://stackoverflow.com/questions/5046835/mongodb-field-order-and-document-position-change-after-update/6453755#6453755 – mickl Feb 06 '20 at 13:37
1

You are entering wrong key while creating new Project object. Change it to the correct key as per your schema and you'll be good to go.

//project schema
const schema = mongoose.Schema({
    projTitle: String,
    todos: []
});

const Project = mongoose.model('Project', schema);

//add a project
app.post('/addProject', (req, res) => {
    const collection = db.collection('projects')
    **const proj = new Project({projTitle: req.body.projTitle});** // changes are here
    collection.insertOne(proj, function(err, results) {
        if (err){
            console.log(err);
            res.send('');
            return
        }
        res.send(results.ops[0]) //retruns the new document
    })
})
Juhil Somaiya
  • 873
  • 7
  • 20
1

Please try to look at the code below.

const collection = db.collection('projects')
const proj = new Project({projTitle: req.body.projTitle}); //make changes here
Juhil Somaiya
  • 873
  • 7
  • 20