Search code examples
mongodbmongoosemongodb-querymongoose-schemamern

Error: TypeError: user.insertOne is not a function using mongoose


I'm having difficulty creating the routes to send to MongoDB. When I return user, it returns the full database. This goes for using User or 'user'. User is a model let User = require('../models/user.model');

 User.findById(req.params.id)
    .then(user => {
        if (!user)
            res.status(404).send("data is not found");
        else
            for(var key in req.body.proposal) {
                //res.send(user.proposal)
                //res.send(user)
                //res.send(User.username)
                user.proposal.insertOne(
                    { 
                        "uid" : req.body.proposal[key].uid,
                        "clientEmail" : req.body.proposal[key].clientEmail,
                        "summary" :req.body.proposal[key].summary,
                        "terms" :req.body.proposal[key].terms,
                        "form" :req.body.proposal[key].form 
                    } //update
                )
            }
     user.save()
        .then(user => res.json(user))
        .catch(err => res.status(400).json('Error: ' + err));   
    })
    .catch(err => res.status(400).json('Error: ' + err));
});

Thank you in advanced!


Solution

  • It should be something like this :

    let proposalArr = [];
    for (const key in req.body.proposal) {
      proposalArr.push({
        uid: req.body.proposal[key].uid,
        clientEmail: req.body.proposal[key].clientEmail,
        summary: req.body.proposal[key].summary,
        terms: req.body.proposal[key].terms,
        form: req.body.proposal[key].form
      });
    }
    user.proposal = proposalArr;
    user.save().............
    

    You can't use .insertOne on result of database query, it's a function of mongoose model to insert new document to collection but not to insert new fields to objects. You need to do just like adding new fields to json object using .js code, but mongoose will keep track of object's changes & when you use .save() it can update the document in collection with all those changes.

    Instead of two DB calls, you can do that in one call, Check : .findByIdAndUpdate() & try below sample code :

    let proposalArr = [];
    for (const key in req.body.proposal) {
      proposalArr.push({
        uid: req.body.proposal[key].uid,
        clientEmail: req.body.proposal[key].clientEmail,
        summary: req.body.proposal[key].summary,
        terms: req.body.proposal[key].terms,
        form: req.body.proposal[key].form
      });
    }
    
    User.findByIdAndUpdate(
      req.params.id,
      {
        proposal: proposalArr
      },
      { new: true }
    )
      .then(user => {
        if (!user) res.status(404).send("data is not found");
        res.json(user);
      })
      .catch(err => res.status(400).json("Error: " + err));