saving unstructured data in mongoose - node.js

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

Related

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;

How to create a mongoose schema dynamically?

I am new in mean and trying to to create a mongoose schema dynamically.
this is my model for deo:
var mongoose=require('mongoose');
Schema=mongoose.Schema;
var deoSchema=new Schema({
name: String
});
module.exports = mongoose.model('deo',deoSchema);
this is how i save it :
var deo = function () { };
deo.prototype.create = function (req, res) {
var deo=new Deo(req.body);
deo.save(function(err,doc){
if(err){
console.log('error occured..'+err);
}
else{
res.json(doc);
}
});
}
now i want to try to store other fileds to store it in mongodb and tried to use {$upsert=true} while saving and edited my model as below
var mongoose=require('mongoose');
Schema=mongoose.Schema;
var deoSchema=new Schema({
name: String,
type:[Schema.Types.Mixed]
});
module.exports = mongoose.model('deo',deoSchema);
but not able to save it and what should i do to save dynamically those fields which are not in schema of mongodb.
i Just tried
this and edited my schema as below and just passed name as required in form
var mongoose=require('mongoose');
Schema=mongoose.Schema;
var deaoSchema=new Schema(Schema.Types.Mixed, {strict: false});
module.exports = mongoose.model('deao',deaoSchema);
in my case i just edited a bit.
const mongoose=require('mongoose');
Schema=mongoose.Schema;
const deaoSchema=new Schema(
{ type : Schema.Types.Mixed},
{strict: false});
module.exports = mongoose.model('deao',deaoSchema);

Able to add to database in MongoDB but not mongoose

I am learning about Mongoose. I am working along this tutorial and running into a stumbling block with adding entries to my database, run through Heroku MongoDB. I am able to add to the existing collection "test1" when I load the app 'trywithmongodb' but I in my Heroku mLab console I do not see anything added to any collections when I access the page "trywithmongoose". Help? Here is the relevant code for in index.js:
var express = require('express');
var mongoose = require("mongoose");
var mongo = require('mongodb').MongoClient;
app.get("/trywithmongodb", function(request,response){
response.send("Looking at the /trywithmongodb page");
var configDB = require('./config/database.js');
//add to the database
mongo.connect(configDB.url , function(err, db) {
var shorturl = db.collection("test1");
var date = new Date();
var newsitejson={original_url: "accessed at", site_number: date.getHours()+":"+date.getMinutes()}
shorturl.insert(newsitejson)
db.close()
})
});
app.get('/trywithmongoose', function (request, response) {
var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
// grab the user model
var User = require('./app/models/user');
// create a new user
var newUser = User({
name: 'Peter ',
username: 'peter45',
password: 'willbehashed',
admin: true
});
// save the user
newUser.save(function(err) {
if (err) throw err;
console.log('User created!');
});
response.send("You are looking at /trywithmongoose");
});
And here's the full file user.js for the schema:
// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// create a schema
var userSchema = new Schema({
name: String,
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
admin: Boolean
});
// the schema is useless so far
// we need to create a model using it
var User = mongoose.model('User', userSchema);
// make this available to our users in our Node applications
module.exports = User;

1 of 2 Mongoose schema not getting initialized

I am new to Node and MongoDB. I am using mongoose to create schemas on Mongo. I have created two schemas in 1 models.js file as shown below
var mongoose = require('mongoose');
var postSchema = new mongoose.Schema({
username: String,
text: String,
created_at: {type: Date, default: Date.now}
});
var userSchema = new mongoose.Schema({
username: String,
password: String,
created_at: {type: Date, default: Date.now}
});
//declaring a model which has schema userSchema
mongoose.model("User", userSchema);
mongoose.model("Post", postSchema);
The problem is that my user schema is getting initialized and works fine. But the posts schema is a problem.
This is the error that I get while starting the server:
C:\Users\rohit\Desktop\projects\chirp\module4\start\node_modules\mo
throw new mongoose.Error.MissingSchemaError(name);
^
MissingSchemaError: Schema hasn't been registered for model "Post".
Here is my snippet from the api.js that actually calls post schema to make database queries
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Post = mongoose.model('Post');
...
router.route('/posts')
.get (function(req, res){
Post.find(function(err, data){
if(err){
return res.send(500, err)
}
return res.send(data)
})
})
Here, is the code snippet from my auth.js file that uses the User Schema and it works fine
var LocalStrategy = require('passport-local').Strategy;
var bCrypt = require('bcrypt-nodejs');
var mongoose = require('mongoose');
var User = mongoose.model('User');
var Post = mongoose.model('Post');
module.exports = function(passport){
// Passport needs to be able to serialize and deserialize users to support persistent login sessions
passport.serializeUser(function(user, done) {
console.log('serializing user:',user._id);
return done(null, user._id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user){
if (err){
return done(err, false)
}
if(!user){
return done('User not found', false)
}
return done(user, true);
})
});
You are not loading your models (User and Post) in your models.js.
Add the following lines after var mongoose = require('mongoose');:
var User = require('./models/user.js'); <-- type your user.js model path here
var Post = require('./models/post.js'); <-- type your post.js model path here

foo.find(...).execFind is not a function - mongoose schema model

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.

Resources