Search code examples
node.jsmongodbmongoose

How to use mongoose and nodejs to insert document without having a schema


I'm using nodejs and mongoose in my project, when I'm trying to add a document to mongodb database, Ifound an emty document, I dont know why ?

Method :

const createUser = async (req, res) => {
try {
 req = matchedData(req)
 const doesUserExists = await userExists(req.email)
 if (!doesUserExists) {
   res.status(201).json(await createItem(req,User))
 }
} catch (error) {
  handleError(res, error)
}
}

createItem :

const createItem = (req = {}, model = {}) => {
return new Promise((resolve, reject) => {
console.log(req)
model.create(req, (err, item) => {
  if (err) {
    reject(buildErrObject(422, err.message))
  }
  resolve(item)
  })
})
}

User Model :

const mongoose = require('mongoose')
const mongoosePaginate = require('mongoose-paginate-v2')

const UserSchema = new mongoose.Schema({})
UserSchema.plugin(mongoosePaginate)
module.exports = mongoose.model('User', UserSchema, 'users')

postman test : enter image description here

can anyone understand why I'm getting en empty result please ?


Solution

  • this could help -> https://mongoosejs.com/docs/guide.html#strict

    im guessing you should have it like

    const UserSchema = new mongoose.Schema({/*....*/}, { strict: false })