I'm a little confused by this part of mongoose, currently i am trying create the habit of structuring my project(using express-generator). I have these part of codes and i am trying to make a get request and return some value from the mongo but in my mind i am not reaching it right.
The app.js is basically the default when i run it for the first time, but to be clear i have line below for my route to work.
app.get('/login', usersRouter);
Then I have the users.js in the routes folder
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
//Connect to localhost
mongoose.connect('mongodb://localhost:27017/LCC');
//Bring models
let User = require('../models/user-model');
router.get('/login', function (req, res) {
User.find({}, function(err, result){
console.log(result);
});
});
And my model in the other folder:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//User Schema
var userProfile = new Schema({
username: String,
password: String
});
module.exports = mongoose.model('Users', userProfile);
My question is, what did i missed? Because in my mind it was supposed to work the console.log and retrieve all the users in mongo. But i only get [] in the terminal (there are six records in the database).
I just copied one route and not all of the code but if something is missing just tell me and i'll edit the post, with mongo driver i can do these queries but i am trying to learn this way by my own. And english is not my first language so sorry for any mistakes.
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/dbname");
var userSchema = mongoose.Schema({
name: String,
age: Number,
});
module.exports = mongoose.model("module", userSchema);
Related
Sorry if I have mixed up the terminology, but I am trying to understand how I can save objects to custom collections dynamically. If I have a app that handles blogs I can only save my blogs to "/My-app/Blogs"
I want to be able to choose a sub-collection dynamically when saving like "/My-app/Good_blogs/Blogs" or "/My-app/Bad_blogs/Blogs"
This is my current code:
app.js
const express = require('express')
const mongoose = require('mongoose')
const app = express()
app.use(express.urlencoded({ extended: true }))
app.use(express.json());
require('dotenv/config')
//Import Routes
const blogRoute = require('./routes/blogs')
app.use('/blogs', blogRoute)
//Connect to DB
mongoose.connect(process.env.MONGOOSE_CONNECT, { useUnifiedTopology: true, useNewUrlParser: true },
() => console.log("Connected to MongoDB"))
app.listen(3000)
Blog.js (Schema)
const mongoose = require('mongoose')
const BlogSchema = mongoose.Schema({
message: String,
})
module.exports = mongoose.model('Blog', BlogSchema)
blogs.js
const express = require('express')
const router = express.Router()
const Blog= require('../models/Blog')
router.post('/', async(req, res) => {
const blog = new Blog(req.body)
await blog.save()
res.sendStatus(200)
})
module.exports = router
From our comments I have deduced you are trying to add documents to a collection whose name is provided in a string. It is not recommended to have multiple collections with the same schema. What you should do is put all your blog posts in one big collection and add a property to query it by that will give you the posts you want.
There is no such thing as a "sub-collection", but you can make a property of type array and store more documents in it.
You can use a schema like so:
const BlogSchema = mongoose.Schema({
message: String,
});
BlogSchema.add({subBlogs: [{type: mongoose.Schema.Types.ObjectID, ref: BlogSchema }]});
The subBlogs property just needs to be added after creation because BlogSchema is undefined until after creation.
subBlogs will now be an array of blog _ids, to which you can push new blogs into, and populate using Mongoose as you would populate any other data.
var express = require('express');
var router = express.Router();
var Product = require('../models/products');
/* GET home page. */
router.get('/', function(req, res, next) {
var products = Product.find();
res.render('shops/index', { title: 'Express' ,Product:products});
});
module.exports = router;
i am new to nodejs and mongodb .I have 5 record in database but the code above is returning 15 records from database
here is the model implemented
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({
imagePath:{type: String,required:true},
title:{type: String,required:true},
description:{type: String,required:true},
price:{type: String,required:true},
});
module.exports = mongoose.model('Product',schema);
find is an asynchronous operation where the result is provided in a callback function. Querying for it would look like that:
Product.find({}, function(err, products) () {
res.json(products);
});
But i can't see why you are getting 15 results...
I'm working on a new app and trying to get mongo set up locally for storage. My api endpoints are getting hit but as soon as I try to actually call a db operation - find or save - it doesn't respond.
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var Person = require('./data/person');
var dbConfig = require('./config');
//database: 'mongodb://localhost:27017/persondb'
var db = mongoose.createConnection(dbConfig.database);
db.on('error', function() {
console.info('Error: Could not connect to MongoDB. Did you forget to run `mongod`?');
});
if (~process.argv.indexOf('mode_dev')) {
global.mode_dev = true;
console.log('Server started in dev mode.');
}
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', router);
router.route('/persons')
.post(function(req, res) {
debugger;
var person = new Person(); // create a new instance of the Person model
person.name = req.body.name;
person.save(function(err) {
debugger;
if (err)
res.send(err);
res.json({ message: 'Person created!' });
});
})
.get(function(req, res) {
Person.find(function(err, persons) {
debugger;
if (err)
res.send(err);
res.json(persons);
});
});
Here's the schema:
data/item.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var personSchema = new Schema({
name: String,
});
module.exports = mongoose.model('Person', personSchema);
I am running mongod before getting my webserver started. As soon as I get to the .save or .find calls, no error is thrown but the callbacks are never hit.
I would connect like this:
mongoose.connect("mongodb://localhost/persondb");
var db = mongoose.connection;
maybe this will help it explains problems using mongoose.createConnection(
if you use createConnection, you need to always reference that connection variable if you include a registered model, otherwise if you use mongoose to load the model, it will never actually talk to your database.
The other solution is to simply use mongoose.connect instead of
mongoose.createConnection. Then you can just use
mongoose.model(‘MyModel’) to load the requested model without needing
to carry around that db connection variable.
I have defined a custom type and I am trying to return all entries from mongo contained in the referenced collection:
Participant.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var participantSchema= new Schema({
email: String,
});
module.exports = mongoose.model('Participant', participantSchema, 'participants')
api.js
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Participant = require('../models/Participant');
router.get('/all', function(req, res) {
var participant = mongoose.model('Participant');
//var participant = new Participant();
console.log(participant);
participant.find().execFind(function (arr,data) {
res.send(data);
});
});
module.exports = router;
But due something fishy, my model does not extend (I assume the default prototype)
participant.find(...).execFind is not a function
TypeError: participant.find(...).execFind is not a function
at /Users/bogdan/private/appName/routes/api.js:13:24
Any help is highly appreciated...
Thanks
execFind was replaced with exec back in one of the 3.x releases of Mongoose.
So you must now call exec instead of execFind.
I am able to save request the data if I explicitly define in my express model the structure, but I am not able to save record if I do not explicitly define the data structure.
For example I am able to save if I have this in my model
....
module.exports = mongoose.model('Form', new Schema({
name: String,
password: String,
admin: Boolean
}));
...
...
but I am not able to save it if I have it like this
module.exports = mongoose.model('Form', new Schema());
Here is my model
// get an instance of mongoose and mongoose.Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// set up a mongoose model and pass it using module.exports
module.exports = mongoose.model('Form', new Schema());
And here is my Router
apiRouter.post('/forms/createForm', function(req, res) {
var form = new Form(req.body);
form.save(function(err) {
if (err) throw err;
console.log('Form saved successfully');
res.json({ success: true });
});
});
Thanks
Ok I got that working.
There is a strict false option that I can use to define the schemaless structure.
Thats how I did it:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// set up a mongoose model and pass it using module.exports
module.exports = mongoose.model('Form', new Schema({}, { strict: false} ));