0

I'm trying to figure out where in the project structure I can create a mongoDB document instance for which I defined a schema before.

I defined my connection in the main index.js file for mongoDB:

var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var express = require('express');
mongoose.connect("mongodb://localhost/db");

and created the schema and document model of the schema inside the "/model" subfolder. I also created an instance of the document schema model and used the method .save() on it, however, nothing happened when I looked inside MongoDB Compass. No database or collection was created.

var mySchema = new mongoose.Schema({name: String, count: Number});
var Test = mongoose.model("Test", mySchema);

var test1 = new Test({name: "Clinton", count: 5});
test1.save(function (err) {
if (err) return handleError(err);
// saved!
});;

Can someone explain me what I have to do to see the created documents, or where I have to define my document instances inside the Node.js structure?

I use express 4.0 with mongoose and some predefined template structures, I am pretty new to the Node.js stack and so I am not sure if I get it right with the complex structure. I started the program in cmd with node index.js. It started and listened on port 3000, but not database or collections / documents were created...

MMMM
  • 3,320
  • 8
  • 43
  • 80
  • If you want send a message to "me" then you need to use the `@` otherwise I'm just not going to see it. Forget the express part and simply try and create a simple listing which connects to mongoose and attempts to create something. You were pointed at the "basics" because you have not yet demonstrated you understand the basics, and I don't see a clear pattern here that demonstrates a valid connection "which awaits a callback" to even get to the state to be able to create a collection or document. If you can show something "reproducible", then there is something to look at. – Neil Lunn May 14 '18 at 12:46
  • This is not a duplicate of the question, which you have marked @NeilLunn Regardless of the other points you have mentioned. This is a message for "you". Not sure what all the "quotes" around parts of your "sentence" that don't need them are about. – Evan Bechtol May 14 '18 at 13:38
  • OP, can you please post more of your code, as requested by Neil? Would like to help you out. – Evan Bechtol May 14 '18 at 13:42
  • somehow , I needed additional code to open a db connection, it was not sufficient what I saw on other tutorials. I got this from scotch.io: var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function() { console.log("DB connection alive"); }); after that, I had a connection to mongoDB and could insert and find new objects / documents – MMMM May 15 '18 at 07:09

0 Answers0