Data seeded with Mongoose not being saved in MongoDB - node.js

I'm trying to add some data to MongoDB using Mongoose, but I'm having trouble getting that data to save to my database. I'm following this tutorial on YouTube (~11 min), but I think the video might be using a different version of Mongoose.
Basically, I have a Product schema defined in a separate JS file, and I'm running a file called productSeeder.js by running node productSeeder.js in terminal with the Mongo daemon running. When I switch to the correct database and type db.products.find() into the Mongo shell, nothing is returned to me.
My productSeeder.js file:
var Product = require('../models/product');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/shopping');
var products = [
new Product({
imagePath: 'images/dummy.png',
price: 9,
title: 'a title',
desc: 'some text'
}),
new Product({
imagePath: 'images/dummy.png',
price: 5,
title: 'a title',
desc: 'some text'
})
];
var done = 0;
for (var i = 0; i < products.length; i++) {
products[i].save(function(err, result) {
if (err) {
console.log(err);
return;
};
done++;
if (done == products.length) {
mongoose.disconnect();
};
});
};
My product.js file:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({
imagePath: {type: String, required: true},
price: {type: Number, required: true},
title: {type: String, required: true},
desc: {type: String, required: true}
});
module.exports = mongoose.model('Product', schema);
Thanks so much, and happy holidays!

Do you know if Mongoose has successfully been connected before you try to save the Products?
One thought could be that since the Db access is async, you're trying to save off items before the connection exists.
You could pass a callback to your connection or use an event listener and wrap your save functions in the connection callback.
mongoose.connection.on('connected', function(){
//save products here
});
I've read of a few cases of Mongoose failing to save without error.
Edit: might be better to listen for .on('open') instead (mongoose docs).

Related

Mongoose populate returns empty array with a simple,non-nested population

I am trying to populate a model but I am getting a empty array in return. I went throught every stack overflow answer but nothing solved my issue.
Here's my main schema:
const companySchema = new Schema({
name:{type:String,required:true},
img:{data: Buffer,contentType: String},
users:[{
name:String,
email:String,
allottedWarehouse:String,
}],
brands:[{type:Schema.Types.ObjectId,ref:'Brand'}],
warehouses:{type:Array},
shops:{type:Array}
})
Here's how I am trying to populate
exports.getCompanyDetails = function(req,res){
Company.findById(req.params.id)
.populate('brands')
.exec(function(err,selectedCompany){
if(err){
res.json('Something went wrong!')
}
console.log(selectedCompany.brands)
res.json(selectedCompany);
})
}
But in database it's just empty brands array,no id reference at all.
When I return it in res.json,it's empty too.
Here's my simple brand schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const BrandSchema = new Schema(
{
name: {type: String, required: true},
packSize:{type: Number, required: true},
})
module.exports = mongoose.model('Brand',BrandSchema);
I so badly need your help on this. Please look at it guys!Tell me where I am going wrong.

Can't save a document to mongodb with mongoose

I have my schema as this
var Schema = mongoose.Schema;
var schema = new Schema({
uid : {type: String, required: true},
title: {type: String, required: true},
description: {type: String, required: true}
})
module.exports = mongoose.model('Task', schema)
In another file, I include this file, and try to seed the db:
var Task = require('../models/task');
var uuid4 = require('uuid4')
var mongoose = require('mongoose')
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/app', {useNewUrlParser: true});
var task = new Task({
uid: uuid4(),
title: 'task3 name',
description: 'task3 desc'
})
task.save(function (err) {
if (err) console.log(err)
})
}
No matter what I do, it won't save the data I want.
Now, when I dive into the db, app database, tasks collection, there are no inserts over there
version: "mongoose": "^5.5.2",
According to this documentation
If you create a custom connection, use that connection's model() function instead.
var connection = mongoose.createConnection('mongodb://localhost:27017/test');
var Tank = connection.model('Tank', yourSchema);
So you need to declare your model from your connection so that it knows which connection to associate the .save() action.
I would recommend creating a dedicated db.js file that handles creating the connection which can then be imported into each of your schema files in order to create the model from the supplied connection.

Mongoose validation and GridsFS

I would like add a mongoose validation in my code but I don't have a ".save method" in my code. It's because I use GridFS who to manage the save in the Database.
My question is simple. How get I a mongoose error with a other method.
This is a example of code.
First part, the schema
var mySchema = new Schema({
name: {
type: String,
required: true
},
color: {
type: String,
required: true
}
});
mongoose.model('mySchema', mySchema);
Second Part, the JS Code
Normally, you have this code.
var mySchema = mongoose.model('mySchema');
function upload(req, res){
var name = req.body.name;
var color = req.body.color;
var myUpload = new MySchema({
name: name,
color: color
})
myUpload.save(function(err){
if(err){
console.log(err)
}
})
}
But me, I don't have this code because GridFS manage all. So, how catch a error while schema execution if i don't have this code, but gridFS ?

How to get data from existing MongoDB database?

I have a database on mlab and now I was starting a new Project and trying to simply get data from there.
The Database has only one collection called Article.
On my Node js project, using Mongoose, I created the Model for it:
var mongoose = require('mongoose');
var articleSchema = new mongoose.Schema({
title: { type: String, required: true },
body: { type: String }
});
var Article = mongoose.model('Article', articleSchema);
module.exports = Article;
The in my controller I just did this:
Article.find({}, function (err, articles) {
res.send(articles);
});
I should receive more than 300 articles but the response is just an empty Array.
I was wondering if I need to run a few more command in order to connect to the db correctly, but I don't know it...
If you want to fetch on an existing Article collection:
var articleSchema = new mongoose.Schema({
title: { type: String, required: true },
body: { type: String }
}, { collection : 'Article' });

Closing DB in Mongoose

I have the following code to insert record in Mongo by using Mongoose.
var mongoose = require('mongoose');
var config = require ('config');
var db = mongoose.createConnection(config.database.address, config.database.dbName);
var strCollectionName = 'category';
var CategorySchema = new mongoose.Schema({
categoryName : {type: String, required: true , unique: true },
categoryTag : {type: String},
categoryDescription : {type: String},
createDate : {type: Date, default: Date.now}
});
var createCategory = function (objCategory)
{
var Category = db.model(strCollectionName, CategorySchema );
var objSchema = new Category(objCategory);
objSchema.save(function (err)
{
if (err)
console.log ("Error");
else
console.log ("Success !!");
});
}
I managed to make it work. But if i try to issue db.close () command inside save it throws error otherwise it is good. My questions is I should not have to close the connection at all ? Will Mongoose automatically takes care it ? - Im worried if the connection pool goes beyond the limit then the entire DB might crash.
To do this properly:
Define your models and tell Mongoose about them at the same time. You can do this before you create the connection.
You were previously telling Mongoose about your schema right when you wanted to use it - you only need to do this once, when you create the schema itself.
You can then open a connection for Mongoose which will work across your whole application (i.e. to use it subsequently, you just have to require('mongoose')):
var mongoose = require('mongoose');
var config = require ('config');
var CategorySchema = new mongoose.Schema({
categoryName : {type: String, required: true , unique: true },
categoryTag : {type: String},
categoryDescription : {type: String},
createDate : {type: Date, default: Date.now}
});
mongoose.model('Category', CategorySchema);
mongoose.connect(config.database.address, config.database.dbName);
If you want to manually create and manage connections you can, using .createConnection as in your example above, but unless you know what you're doing it's better to just use Mongoose's default connection.
To create a category:
// if you're in a different file to where you created your CategorySchema, var these:
var mongoose = require('mongoose'),
Category = mongoose.model("Category");
var createCategory = function (objCategory) {
var newCategory = new Category(objCategory);
newCategory.save(function (err) {
if (err)
console.log ("Error");
else
console.log ("Success !!");
});
}

Resources