can't insert data using mongoose - node.js

i am new in mean stack i completed update,delete,and get data but can't insert data in mongoose can anyone help me please.thanks in advance below is my code.
var express = require('express');
var mongojs = require('mongojs');
var db = require('mongoose');
var bodyParser = require('body-parser');
var app = express();
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
db.connect('mongodb://localhost/contactlist');
var db1 = db.connection;
db1.on('error', err);
db1.once('open',startserver);
function err(){
console.log('connection error:');
}
function startserver(){
console.log('start');
app.listen(3000);
}
var contactdetails1 = new db.Schema({
name:String,
email:String,
password:String,
number:String
});
db1.model('Contactdetails',contactdetails1);
app.post('/contactList',function(req,res){
console.log("Get insert request"+req.body);
//var contactList = new ContactList(req.body);
var contactdetails1 = new db.Schema({
name:req.body.name,
email:req.body.email,
password:'',
number:req.body.number
});
contactdetails1.save(function(err,data) {
if (err) {
response = {
"status":0,
"error":err,
};
}else{
response = {
"status":1,
"data":data,
"message":"User registered successfully"
};
}
console.log(response);
res.json(response);
});
});
when inserting data at that time below error show
Undefined type Test at name
Did you try nesting Schemas? You can only nest using refs or arrays.
at Function.Schema.interpretAsType (/usr/lib/node_modules/mongoose/lib/schema.js:666:11)
at Schema.path (/usr/lib/node_modules/mongoose/lib/schema.js:545:29)
at Schema.add (/usr/lib/node_modules/mongoose/lib/schema.js:429:12)
at new Schema (/usr/lib/node_modules/mongoose/lib/schema.js:100:10)
at /var/www/html/contactlistappmvc/server.js:53:25

var contactdetails1 = new db.Schema({
name:req.body.name,
email:req.body.email,
password:'',
number:req.body.number
});
You should be saving a model, not a schema. What you've done here is pass an object to the schema. Documents are instances of Models, not schemas. A schema is just an object definition.
Instead of what you've done here, why don't you do
var ContactModel = mongoose.model('Contactdetails',contactdetails1);
var contactModel = new ContactModel({
name:req.body.name,
email:req.body.email,
password:'',
number:req.body.number
})
And then do a contactModel.save()

Related

node.js mongoose find() not value

route/signup.js
var express = require('express');
var router = express.Router();
const User = require('../model/user');
var mongoose = require('mongoose');
function userFind(value){
return User.find({user_id:value}).exec();
};
router.get('/',function (req,res) {
res.render('login/signup');
});
router.post('/',async function (req,res,next){
try{
let userid =req.body.id;
console.log(userid); //abcdefg
const user = await userFind(userid);
console.log(user); // []
}catch(err){
next(err);
}
})
module.exports = router;
model/user.js
const mongoose = require('mongoose')
var Schema = mongoose.Schema;
const userSchema = new Schema(
{ user_id : {type:String,required:true, unique:true},
user_password : {type:String, required:true, select:false},
user_name: {type:String, required:true},
user_email : {type:String,required:true,unique : true},
user_birth : {type:String,require:true},
},{versionKey:false},
{collection: 'user'}
);
module.exports = mongoose.model('user',userSchema);
data inside mongodb.
{
"_id": {
"$oid": "60413c7c48e5e61187cc4eeb"
},
"user_id": "abcdefg",
"user_password": "test111",
"user_name": "세글자",
"user_email": "test#naver.com",
"user_birth": "884455"
}
app.js
var express = require('express');
var mongoose = require('mongoose');
const bodyParser = require('body-parser');
var db = mongoose.connection;
db.on('error', console.error);
db.once('open', function(){
// CONNECTED TO MONGODB SERVER
console.log("Connected to mongod server");
});
mongoose.connect("mongodb+srv://testing1:7894#cluster0.9hxjc.mongodb.net/data?
retryWrites=true&w=majority", { useNewUrlParser: true, useUnifiedTopology:
true });
var app = express();
var test = require('./route/index');
var test2 = require('./route/signup');
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.set('views',__dirname+'/views'); // ==
app.set('views',path.join(__dirname, 'views'));
app.set('view engine','ejs');
app.engine('html',require('ejs').renderFile);
app.use('/',test);
app.use('/signup.ejs',test2);
app.listen(3000,function(){
console.log('hello world');
});
Hello, I am studying using mogoose and node.js. I ran mongoose find() but the result was only []. I don't know why this is so, I would appreciate it if you let me know. And if it is findOne(), how should I write it? I tried writing it once, but it turned out to be null.
Through chatting in comments we found the issue. The model is called user:
module.exports = mongoose.model('user',userSchema);
Which mongoose will connect to a collection named users (plural) in MongoDB. That collection was indeed empty. There was only content in a collection named user.

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

Can't insert into MongoDB with Mongoose

I'm trying to insert an object in MongoDB with Mongoose, but without success.
In './models/user,js' I have:
var mongoDatabase = require('./db'); //I've connected to localhost here
var database = mongoDatabase.getDb();
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
user: String,
adress: String,
});
userSchema.methods.testmethod = function(){
console.log('test');
}
userSchema.methods.insert = function (obj) { //this works but what is the point to use Mongoose If I do it that way
database.collection("users").insertOne(obj, function(err, res) {
if(err) throw err;
console.log("1 record inserted");
});
}
var User = mongoose.model('User', userSchema);
module.exports = User;
In './controllers/user.js'
var express = require('express');
var router = express.Router();
var User = require('../models/user');
router.post("/", function(request, response) {
var obj = new User({
user: request.body.name,
adress: request.body.adress,
});
obj.testmethod(); //works fine
obj.insert(obj); //throws an error
User.insertOne(obj, function(err, res) { //error: insertOne is not a function
if(err) throw err;
console.log("1 record inserted");
});
});
module.exports = router;
I have tried few more ways to do it, but without result. Can someone help me?
You shouldn't be using whatever mongodb object you're creating in './db' to do this work, mongoose takes care of it for you. Try simplifying down to this:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
user: String,
adress: String,
});
module.exports = mongoose.model('User', userSchema);
Then in your controller code
var express = require('express');
var router = express.Router();
var User = require('../models/user');
router.post("/", function(request, response, next) {
var user = new User({
user: request.body.name,
adress: request.body.adress,
});
user.save(function(err, u) {
if (err) return next(err);
return res.json(u);
});
});
module.exports = router;
Somewhere in your app startup code (often in app.js or similar location) you'll want to call mongoose.connect(<connection url>), normally prior to setting up routes.
Note you can also call insert() explicitly, but it's a static method on the model object, like so:
User.insert({user: 'bob', address: 'somewhere, nh'}, cb)

TypeError: Object #<Object> has no method 'find'

I follow actually a training in nodejs, express and mongo.
I developed a rest webservice but when I try to access it, I have the current exception :
TypeError: Object # has no method 'find'
I don't understand what's happen exactly because my code seems correct and the same that in the tutorial.
Schema Definition
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var bookModel = new Schema({
title:{
type:String
},
author:{type:String},
genre:{type:String},
read:{type:Boolean,default:false}
});
module.export= mongoose.model('Book',bookModel);
Definition of my service
var express = require('express'),
mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/bookAPI');
var Book = require('./models/bookModel');
var app = express();
var port = process.env.PORT || 3000;
var bookRouter = express.Router();
bookRouter.route('/books')
.get(function(req,res){
Book.find(function(err,books){
if(err)
console.log(err);
else
res.json(books);
});
});
app.use('/api', bookRouter);
app.get('/',function(req,res){
res.send('welcome to my api 2000');
})
app.listen(port, function(){
console.log('Running on PORT: ' +port);
});
try this:
var Book= mongoose.model('Book',bookModel);
export module like this:
module.exports = {
Book: Book
};
And import with following code:
var Book = require('./models/bookModel').Book;
after that write find query
Book.find({},function(err,books){
if(err)
console.log(err);
else
res.json(books);
});

How do I partially update an array inside and object in MongoDB so the new value is added to the array

Given the following schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var favoriteSchema = new Schema({
dishes: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Dish'
}],
postedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
}, {
timestamps: true
});
var Favorites = mongoose.model('Favorite', favoriteSchema);
module.exports = Favorites;
and the following router
var bodyParser = require('body-parser');
var express = require('express');
var mongoose = require('mongoose');
var Favorites = require('../models/favorites');
var Verify = require('./verify');
var favoritesRouter = express.Router();
favoritesRouter.use(bodyParser.json());
favoritesRouter.route('/')
.post(Verify.verifyOrdinaryUser, function(req,res,next){
req.body.postedBy = req.decoded._doc._id;
console.log('nana ' + req.body.postedBy);
Favorites.create(req.body,function(err,fav){
if(err) throw err;
fav.dishes.push(req.body);
fav.save(function(err,fa){
if(err) throw err;
res.json(fa);
})
});
});
module.exports = favoritesRouter;
Every time i do the post requires from postman, I`m attaching the dish ID to the body of the request.
{
"_id": "577a996155d73cf02b0d516f"
}
I could not come up with a solution to insert this ID into the array, instead of re-creating the whole object with only 1 id inside the array. Am i making something wrong, or something else has to be done in order to do the logic i want?
You're going to want to query the database to find the previously saved object, append to the array, mark as modified, then save. It will look something like this:
var bodyParser = require('body-parser');
var express = require('express');
var mongoose = require('mongoose');
var Favorites = require('../models/favorites');
var Verify = require('./verify');
var favoritesRouter = express.Router();
favoritesRouter.use(bodyParser.json());
favoritesRouter.route('/')
.post(Verify.verifyOrdinaryUser, function(req,res,next){
req.body.postedBy = req.decoded._doc._id;
console.log('nana ' + req.body.postedBy);
Favorites.findById(someID, function(err, fav){
if(err) throw err;
fav.dishes.push(req.body);
fav.markModified('dishes')
fav.save(function(err,fa){
if(err) throw err;
res.json(fa);
})
});
});
You'll need to figure out how you're getting the ID in there. You could use a dynamic endpoint:
favoritesRouter.use(bodyParser.json());
favoritesRouter.route('/:id')
.post(Verify.verifyOrdinaryUser, function(req,res,next){
var someID = req.params.id
})
Or you could do a search for who posted it (.find({postedBy: req.decoded._doc._id},... instead of .findById(someID,...), or something else

Resources