How do I save a object to custom collection? - node.js

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.

Related

data is not saving in mongodb compass .inside thunder client body i have passed a json according to model schema . but data is not saving in mongo db

data is not saving in mongodb compass . i have used node js to connect to mongodb . a router is also there . model schema is also present .inside thunder client body i have passed a json according to model schema . app listen is working fine and connection to mongodb is also successful . but i could not see those passed data in my mongodb.literally i have tried everything but could not get any solution how to save my data ?
db.js (mongo server)
const mongoose = require('mongoose');
const mongoURI = "mongodb://localhost:27017/"
const connectToMongo = ()=>{
mongoose.connect(mongoURI, { useNewUrlParser: true,useUnifiedTopology:true },()=>{
console.log("Connected to Mongo Successfully");
})
}
module.exports = connectToMongo;
index.js (express and mongo server)
const connectToMongo = require('./db'); //here we import db.js from the above
const express = require('express');
connectToMongo();
const app = express();
const port = 3000;
app.use(express.json());
// Available Routes
app.use('/api/auth', require('./routes/auth')) //one route ./api/auth is the route
app.listen(port, () => {
console.log(`iNotebook backend listening at http://localhost:${port}`)
})
auth router
const express = require("express")
const User = require("../models/User") //User schema described below.
const router = express.Router()
router.get("/",(req,res)=>{
console.log(req.body)
const user=User(req.body)
user.save()
res.send(req.body)
})
module.exports = router
User schema inside model folder
const mongoose = require('mongoose');
const { Schema } = mongoose;
const UserSchema = new Schema({
name:{
type: String,
required: true
},
email:{
type: String,
required: true,
unique: true
},
password:{
type: String,
required: true
}
});
const User = mongoose.model('user', UserSchema);
module.exports = User;
picture of thunder client
here you can see https://localhost:300/api/auth is the router . in body i have given name ,email,password and response i am getting right . and also it is showing connected to mongo successfully.
picture of mongodb compass.
where my passed body data that is name,email,password is saving in mongodb compass
You should instantiate the new instance of User with new and await the Promise after save:
router.post("/", async (req,res)=>{
try {
const user= new User(req.body);
await user.save();
res.send(req.body);
} catch (e) {
res.send('error');
}
})
module.exports = router

mongodb & mongoose: How to auto create new collection when saving a document in it

Program description: I have a program that accepts a post request (request) of a "hometask" with its name, description, importance and group parameters provided. I need the provided group parameter to be identified as a collection name in the database (each collection is going to correspond to specific group and so each group will have a collection of hometasks-documents). Each new document should be created with Mongoose schema object.
Problem: I know that in Python's pymongo when addressing an unexisting collection it's being created automatically, however, in mongoose this turns out not to be the case. I have trouble providing the collection name to the new document-object. When providing {collection: request.group} in a new object in api/hometask.js, the error message started appearing when new requests were made: MongooseError: document must have an _id before saving. I still cannot understand what can be the cause of this problem. I will appreciate any help!
Main folder architecture:
server.js
const express = require('express')
require('dotenv').config()
const mongoose = require('mongoose')
const morgan = require('morgan')
const path = require('path')
let app = express();
const port = process.env.PORT || 3000;
mongoose.connect(process.env.uri, { useNewUrlParser: true })
.then(db => console.log('[ok] connected to db))
.catch(err => console.error(err))
app.use(express.json())
app.use(express.urlencoded({extended: false}))
app.use(morgan('dev'))
app.use('/api/hometasks', require('./api/hometask'))
app.use('/', express.static(path.join(__dirname, '../dist')))
app.listen(port)
api/hometask.js
const express = require('express');
const router = express.Router();
const Record = require('../models/hometask')
router.post('/', async (req, res) => {
let request = req.body
const record = new Record(request, {collection:request.group});
try {
await record.save();
res.json({
status: 'success'
});
} catch (err) {
console.log(err)
}
})
module.exports = router
models/hometask.js
const mongoose = require('mongoose');
const { Schema } = mongoose;
let Record = new Schema({
name: {
type: String,
required: true
},
description: {
type: String,
required: true
},
importance: {
type: Boolean,
required: true
},
group: {
type: String,
required: true
}
});
module.exports = mongoose.model('hometask', Record);
In mongoose the collection name is set per model, not per document.
Note that the Model constructor does not take an options object.
You should be setting the collection name in the call to mongoose.model when you create the model, not when you create a document from that model.

Mongoose create multiple Connections

I'm following Mongoose Connection Docs to create multiple Databases Connections on express app. When i import my schema scoped to a connection i can't use models functions such like .find || .findOne etc.. and i get the next error
UserSchema.find is not a function
Is there something that i miss to add or is something i'm making wrong ??
Here is Schema code:
models/user.js
const { Schema } = require('mongoose');
const UserSchema = new Schema({
name: { type: String},
lastname: { type: String}
});
module.exports = UserSchema;
And then i create the connection with the model scooped to it.
databases/connection_1.js
const mongoose = require('mongoose');
const { Keys } = require('../keys');
const conn = mongoose.createConnection(
`mongodb://${Keys.DatabaseUser}:${Keys.DatabasePassword}#${Keys.DatabaseHost}/${Keys.DatabaseShema}`
, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: true
});
conn.model('User', require('../models/user'), 'Users')
module.exports = conn;
But when i try to use my Schema to fetch the data of the Database i get next error:
UserSchema.find is not a function
routes/index.js
const app = require('express').Router();
const UserSchema = require('../models/user');
app.get('/index', async (req,res) => {
console.log(await UserSchema.find({name: 'Jhon Doe'}))
})
module.exports = app;

Query parameter from req.params.foo into mongoose find() not working or returning empty array

I'm coding up a simple demo rest-api, the default /api route work just fine, returning all the results(image below), but I'm hitting a roadblock. Which is that when I type: http://localhost:5050/api/interpol where
/interpol maps to api/:params I'm getting back an empty array, instead of the document matching the artist.
As a side note, I'm running a 32bit Ubuntu 14.04(didn't realize it till after), so I had to downgrade both mongodb and mongoose to get them working together, as a consequence I'm using Mongodb 2.2.6 & Mongoose 4.0.8. Thanx in advance.
Model
// Dependencies
const mongoose = require('mongoose');
//Mongoose Schema
const Albums = new mongoose.Schema({
title : { type: String },
releaseYr : { type: Date }
});
const MusicSchema = new mongoose.Schema({
artist : { type: String },
albums : [Albums]
});
mongoose.model('Music', MusicSchema);
module.exports = mongoose.model('Music');
Router
// Dependencies
const express = require('express');
const Music = require('../models/musicModel');
const musicRouter = express.Router();
// Routes
musicRouter.get('/', (req, res) => {
Music.find({}, (err, artists) => {
res.json(artists)
})
});
musicRouter.route('/:artistName').get((req, res) => {
const artistName = req.params.artistName;
Music.find({ artist: artistName }, (err, artist) => {
res.json(artist)
});
});
module.exports = musicRouter;
App
// Dependencies
const express = require('express'),
bodyParser = require('body-parser'),
Mongoose = require('mongoose'),
Joi = require('joi');
// Initiate express
const app = express();
// Import musicRouter to handle api routes
const musicRouter = require('./api/musicRouter');
// Downgraded to Mongodb 2.2.6 & Mongoose 4.0.8
// Connect to Mongo database via Mongoose
Mongoose.connect('mongodb://localhost:27017/music1', {useNewUrlParser: true});
// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Send routes to musicRouter
app.use('/api', musicRouter);
module.exports = app;
As with all JavaScript, Mongodb does a case-sensitive search.
You're querying { artist: 'interpol' } But referring from the image, you've saved it as Interpol.
So either send your request as /api/Interpol or make a case-insensitive search using regex as detailed here

Module exports in mongoose

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);

Resources