Vlad Tanasie
Vlad Tanasie

Reputation: 63

MongoDB schema does not insert property when using with insertOne function

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

Upvotes: 1

Views: 702

Answers (3)

competitive coder
competitive coder

Reputation: 21

Please try to look at the code below.

const collection = db.collection('projects')
const proj = new Project({projTitle: req.body.projTitle}); //make changes here

Upvotes: 1

Juhil Somaiya
Juhil Somaiya

Reputation: 943

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

Upvotes: 1

mickl
mickl

Reputation: 49945

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.

Upvotes: 2

Related Questions