Home > OS >  Mongoose not creating document on mongodb
Mongoose not creating document on mongodb

Time:01-22

I am using Next.js and MongoDB (mongoose) to make an education portal website. The school admin can add important notices from their dashboard and the student can view them from theirs. Most mongoose operations have to be done in an API that next.js provides them self so my code to create the document on MongoDB is located in /API/ directory. Code:

/**
 * @param {import("next").NextApiRequest} req
 * @param {import("next").NextApiResponse} res
 */

import circulars from '../../../model/hw'

export default async function stuffss(req, res) {
    try{
        const {number, text} = req.body
        console.log("Connecting to mongo")
        mongoose.connect("mongodb srv://usernameherer:[email protected]/stuff?retryWrites=true&w=majority")
        console.log("Connected to mongo")
    
        console.log("Creating document")
        const createdCircular = await circulars.create(req.body)
        
        console.log("Created document")
        res.json({ createdCircular })
    }
    catch(error) {
        console.log(error)
        res.json({ error })
    }
}

The circulars schema:

const mongoose = require('mongoose')



const circularsSchema = new mongoose.Schema({
    number: {
        unique: true,
        required: true,
        type: Number
    },
    text: {
        required: true,
        type: String
    }
})

const circulars = mongoose.models.circularss || mongoose.model("circularss", circularsSchema)

export default circulars

Sending a post request using insomnia gives the following result:

{
    "createdCircular": {
        "number": 15463,
        "text": "loreum ipsum",
        "_id": "63cb86421ca543a731cb39c3",
        "__v": 0
    }
}

but when I go and look for it on the MongoDB website it doesn't have any results. I believe it may be because of how I am connecting or that I am not sending it properly to a collection.

This is the structure of my database:
Stuff -> circulars


Is there a way to connect to the 'stuff' database and 'circulars' collection?

CodePudding user response:

Looks like that the database needs to be specified in connection string.

E.g.

...clusteridhere.mongodb.net/stuff?retryWrites=true&w=majority

Ref: https://mongoosejs.com/docs/connections.html

CodePudding user response:

Here is how I fixed this issue. In my schema I had put the same circulars which created created a new collection for it, I also had to remove await from mongoose.connect. This combined fixed the issue for me. You should also make sure that mongoose.models.name is the same as the mongoose.model("name", schema)

  • Related