I have problem with print items in console.log or res.json from database.
what am I doing wrong
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test');
var Schema = mongoose.Schema;
var productSchema = new Schema({
title: String,
price: Number
});
var product = mongoose.model('product, productSchema');
mongoose.connect(db);
var db = 'mongodb://localhost/product';
router.get('/books', function(req, res) {
console.log('getting all products');
product.find({})
.exec(function(err, product) {
if (err) {
res.send('errror');
} else {
console.log(product);
res.json(product);
}
})
});
name of database products is : db.product
Thanks
Error:
C:\Users\Turqus\Desktop\node\products\node_modules\mongoose\lib\index.js:382
throw new mongoose.Error.MissingSchemaError(name);
^
MongooseError: Schema hasn't been registered for model "product, productSchema".
Use mongoose.model(name, schema)
at Mongoose.model (C:\Users\Turqus\Desktop\node\products\node_modules\mongoose\lib\index.js:382:13)
You have to make the Database Connection first.
change this
var product = mongoose.model('product, productSchema');
to
var product = mongoose.model('product', productSchema);
mongoose.model() accepts two parameter the name of the collection your model is for and the 2nd the Schema
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test');
var Schema = mongoose.Schema;
var productSchema = new Schema({
title: String,
price: Number
});
var product = mongoose.model('product', 'productSchema');
router.get('/books', function(req, res) {
console.log('getting all products');
product.find({})
.exec(function(err, product) {
if (err) {
res.send('errror');
} else {
console.log(product);
res.json(product);
}
})
});
Related
I am a beginner.
I have two mongoose schema, orders and customers.
orders schema
const mongoose = require("mongoose");
const orderSchema = new mongoose.Schema({
customer: {type: mongoose.Schema.Types.ObjectId, ref: "Customer"}
});
module.exports = mongoose.model("Order", orderSchema);
customers schema
const mongoose = require("mongoose"),
passportLocalMongoose = require("passport-local-mongoose");
const customerSchema = new mongoose.Schema({
name: String,
email: String
username: String,
password: String
});
customerSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("Customer", customerSchema);
This is my code when I insert new order
const Orders = require("../models/orders");
Orders.create({customer: req.user});
I want to console.log() all the orders and customers by using .populate()
Here is my code
Orders.find({}).populate("customers").exec((err, order) => {
if(err) {
console.log(err);
} else {
console.log(order);
}
});
I want to get the customer's id, name, and email but the problem is I only get the customer's id
Orders.find({}).populate("customer").exec((err, order) => {
if(err) {
console.log(err);
} else {
console.log(order);
}
})
or you can try
Orders.find({}).populate({path:"customer"}).exec((err, order) => {
if(err) {
console.log(err);
} else {
console.log(order);
}
})
I'm getting an error running router.patch() code to update a product on a cloud-based mongoose database. I'm using Postman to simulate the update. Postman's error is showing, "req.body[Symbol.iterator] is not a function." Here is the relevant code:
Products.js:
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Product = require('../models/product');
router.patch('/:productId', (req, res, next) => {
const id = req.params.productId;
// don't want to update both fields if not needed
const updateOps = {};
// loop through all the operations of the request body
for (const ops of req.body) {
updateOps[ops.propName] = ops.value;
}
Product.update({_id: id}, { $set: updateOps })// $set is a mongoose object
.exec()
.then(result => {
console.log(result);
res.status(200).json(result);
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
{req.body.newName, price, req.body.newPrice} ;
res.status(200).json({
message: 'Updated product',
});
});
module.exports = router
Product.js:
const mongoose = require('mongoose');
const productSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: String,
price: Number
});
// export the schema into the Mongoose model
module.exports = mongoose.model('Product', productSchema);
Any help would be greatly appreciated. :-)
As I commented, this part is likely your problem:
for (const ops of req.body) {
updateOps[ops.propName] = ops.value;
}
Since req.body is an Object, I think you want:
for (let [key, value] of Object.entries(req.body)){
updateOps[key.propName] = value;
}
Or something similar.
I am beginner of nodejs and mongodb. I am inserting data to collection using mongoose ORM and model but not insert. Validation is working correct but data is not insert after filling complete data. I have not create collection in database manually. should I create collection manually in mongodb or create automatically when inserting document.
productsController
var mongoose = require('mongoose');
var db = require('../config/db_config');
var Product = require('../models/product');
//var Product = mongoose.model('Products');
var productController = {};
productController.add = function(req, res) {
var params = req.body;
if(!params) {
res.status(400).send({message: "Data can not be empty"});
}
var productData = new Product({
product_name : params.product_name,
price : params.price,
category : params.category
});
console.log(productData);
productData.save(function(err, product) {
if (err){
res.status(400).send({message:'Unable to save data! ' + err});
}else{
res.status(200).send({message:'Data has been saved! ' + product });
}
});
};
module.exports = productController;
Models code is here
var mongoose = require('mongoose');
var db = require('../config/db_config');
var Schema = mongoose.Schema;
var productSchema = new Schema({
product_name: { type: String, required: 'Product name cannot be left blank.' },
price: { type: String, required: 'Product price cannot be left blank.'},
category: { type: String , required: 'Product category cannot be left blank'},
updated_at : {type: Date, default: Date.now}
});
module.exports = mongoose.model('Products', productSchema);
routes file code is here:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Product = require('../models/product.js');
var productsController = require('../controllers/productsController');
router.post('/add',productsController.add);
module.exports = router;
DB config file
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
var db = mongoose.createConnection('mongodb://localhost:27017/nodeweb', function(err,db){
if(err){
throw err;
console.log(err);
} else {
console.log('Successfully connected to database!');
}
});
module.exports = db;
I have insert controller, model and routes file code.
Please correct your method -
Controller function
exports.add = function(req, res) {
var new_product = new Products(req.body);
// you have define Products not Product
console.log(new_product);
new_product.save(function(err, product) {
console.log('add data');
if (err){
res.send(err);
}else{
res.json(product);
}
});
};
and for good practice in node js - i think you can start with express-app-generator
This Helps to make simple routing, with generic responses and in-built express middlewares with loggers.
I have resolved problem. database connection work with connect method.
mongoose.connect('mongodb://localhost:27017/nodeweb', {useMongoClient: true}, function(err,db){
if(err){
throw err;
console.log(err);
} else {
console.log('Successfully connected to database!');
}
});
I have a nested schema defined with mongoose:
//application.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Category = require('./category.js');
var Application = new Schema({
title : String,
cats : [Category]
});
Application.virtual('app_id').get(function() {
return this._id;
});
module.exports = mongoose.model('Application', Application);
and
//account.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var Application = require('./application.js');
var Account = new Schema({
username: String,
password: String,
apps: [Application]
});
Account.plugin(passportLocalMongoose);
module.exports = mongoose.model('Account', Account);
Now if I try to push to apps which is an array in account like this:
app.post('/application', function(req,res){
var name = req.user.username;
var newApp = new Application();
newApp.title = req.body.title;
console.log(newApp);
Account.findOneAndUpdate({username : name},
{$push: {apps: newApp}},
{safe: true, upsert: true},
function(err, model){
if (err){
console.log(model);
console.error("ERROR: ", err);
res.status(500).send(err);
}else{
res.status(200).send({"status":"ok"});
}
}
);
});
I get the error:
{ title: 'dogs', _id: 564f1d1444f30e0d13e84e7b, cats: [] }
undefined
ERROR: { [CastError: Cast to undefined failed for value "[object Object]" at path "apps"]
message: 'Cast to undefined failed for value "[object Object]" at path "apps"',
name: 'CastError',
type: undefined,
value: [{"title":"dogs","_id":"564f1d1444f30e0d13e84e7b","cats":[]}],
path: 'apps' }
what am I doing wrong?
EDIT:
Found the answer in this question
Practically I need to import the schema not the object
//account.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var ApplicationSchema = require('./application.js').schema; //<-- .schema was added
var Account = new Schema({
username: String,
password: String,
apps: [ApplicationSchema]
});
Account.plugin(passportLocalMongoose);
module.exports = mongoose.model('Account', Account);
To save the Application reference within the Account model's apps embedded document field, push the _id value in the Application model's callback on save:
account.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var Application = require('./application.js');
var Account = new Schema({
username: String,
password: String,
apps: [{type: Schema.Types.ObjectId, ref: 'Application'}]
});
Account.plugin(passportLocalMongoose);
module.exports = mongoose.model('Account', Account);
app.js
app.post('/application', function(req, res){
var name = req.user.username;
var newApp = new Application({
title: req.body.title
});
console.log(newApp);
newApp.save(function (err){
if (err) return handleError(err);
Account.findOne({ username: name }, function (err, doc){
if (err) return handleError(err);
doc.apps.push(newApp._id);
doc.save();
res.status(200).send({"status":"ok"});
});
});
});
Or using promises as:
const handleError = err => console.error(err);
app.post('/application', (req, res) => {
const name = req.user.username;
const newApp = new Application({
title: req.body.title
});
newApp.save().then(result => (
Account.findOneAndUpdate(
{ "username": name },
{ "$push": { "apps": result._id } }
)
)
.then(result => res.status(200).send({"status":"ok"}))
.catch(handleError);
});
[Solved - silly mistake in the model]
I have been trying to refer and populate in mongoose and expressjs, but its not working at all. I have followed these:
1. Mongoose examples
2. Mongoose populate
I created three files:
1) models/profile.js
var mongoose = require('mongoose'), Schema = mongoose.Schema, ObjectId = Schema.ObjectId;
var profileSchema = new Schema({
name: String
});
module.exports = mongoose.model('Profile', profileSchema);
2) models/work.js
var mongoose = require('mongoose'), Schema = mongoose.Schema, ObjectId = Schema.ObjectId;
var workSchema = new Schema({
title: String,
creditsFor: [{type: Schema.Types.ObjectId, ref: 'profile'}],
});
module.exports = mongoose.model('Work', workSchema);
3) controllers/work.js
var Work = require('../models/work.js'), fs = require('fs'), mongoose = require('mongoose');
......
exports.create = function(req, res) {
credits = [];
credits.push(mongoose.Types.ObjectId('5174a9ec993af25b01000003')); // I already created a 'Profile' and copy-pasted the _id
var work = {
title: req.body.title,
creditsFor: credits
}
var workObj = new Work(work);
workObj.save(function(err, data) {
if(err) {
throw err;
} else {
req.flash('info', 'Work item saved.');
res.redirect('/work/' + data._id);
}
});
}
.......
exports.show = function(req, res) {
var work = req.params.work;
Work.findOne({_id: work})
.populate('creditsFor')
.exec(function(err, data) {
if(err) {
throw err;
} else {
console.log(data);
res.render('site/work/show', {work: data, message: req.flash('info')});
}
});
}
When using populate(), returned creditsFor is null. When I comment populate(), it is a string(?), like this:
{
title: 'My Title',
creditsFor: '5174a9ec993af25b01000003'
}
Couldn't figure out whats going wrong. I tried to bring both the models in a single file, still nothing.