Insert an array of objects into mongodb with nodejs - javascript

Now I am using clmtrackr library to detect emotions from the webcam and I want to save this emotions Here is my node.js code to save the values in mongodb
exports.storeemotion = function (emotions, callback){
var eshema= new emotioncollection({
emotions: [emotions]
});
eshema.save(function(err) {
});
callback({"status":"emotion remote done"});
}
and the schema code is
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//var bcrypt = require('bcrypt-nodejs');
// search results schema
var ResultaSchema = new Schema({
emotions:[{emotion: String, value: String}]
});
module.exports = mongoose.model('emotioncollection',ResultaSchema);
emotions should be like that (check this image).
but the mongo saved an empty array (check this image).

The emotions parameters of your storeemotion function is already an array, so you just have to pass that parameters as is, not in another array:
exports.storeemotion = function (emotions, callback) {
var eshema = new emotioncollection({
emotions: emotions // <= your schema already expects an array of objects
});
eshema.save(function(err) {
if (err) return callback({"status": "error"});
callback({"status": "emotion remote done"});
});
}

Related

javascript access form data from inside mongoose schema hooks

I have a form which I have separated its content into two mongodb schema
I would like to read variables which are inside node.js/express.js directly in mongoose schema hooks
either through the pre or post hooks of the schema. these are my files
express.js
var firstName = req.body.first_name;
var lastName = req.body.last_name;
var fullName = firstName+' '+lastName;
var employmentDate = req.body.employment_date;
var responsibility = req.body.responsibility;
userschema.full_name = fullName;
userschema.first_name = firstName;
userschema.last_name = lastName;
userschema.save(function (err, result){
});
/******************express UPDATE START**********/
user = new userschema(req.body)
employment = new employmentObject(req.body)
employment.employment_date= employmentDate;
employment.responsibility= responsibility;
/******************express UPDATE ENDS**********/
Schema.js
var userSchema = mongoose.Schema({
full_name : String,
other_name : String,
last_name : String,
email : String
});
userSchema.pre('save', function (){
//obtain values from form field
var field1 = employmentDate;
var field2 = responsibility;
const employmentObject = this.model('employment-detail');
/******************schema UPDATE START**********/
var emp_Date = employmentObject.employment_date;
var duties = employmentObject.responsibility;
/******************schema UPDATE ENDS**********/
employmentObjectins = new employmentObject({
'employment_date': formField1,
'responsibility' :formField2
});
employmentObjectins.save(function (err){
if(err){
console.log(err+' error saving object');
}
else{
console.log('no error in saving object');
}
});
});
This is the just the summarized content, it is longer than this. But this is the main concept.
The major areas is in getting express.js content into the model's schema
UPDATE
employmentDate and responsibility is not in the userSchema but it is in the employmentSchema
How can I get the fields which are not in userSchema (the main schema) but are in the employmentSchema
( the second schema)
SECOND UPDATE
With the modification above it is producing error
ParallelSaveError: Can't save() the same doc multiple times in parallel. Document:
What am i doing wrong
THIRD UPDATE
When I made modification based on what you said, I discovered that when I have two models
declared in express.js with their model fields/variables and I call the second model in the
pre hook of the first model it was giving me this error
Can\'t save() the same doc multiple times in parallel.
After making modification to the code. These are the files which exist
Express.js
var firstName = req.body.first_name;
var lastName = req.body.last_name;
var fullName = firstName+' '+lastName;
var employmentDate = req.body.employment_date;
var responsibility = req.body.responsibility;
userschema.full_name = fullName;
userschema.first_name = firstName;
userschema.last_name = lastName;
userschema.save(function (err, result){
});
employment.employment_date= employmentDate; <---
employment.responsibility= responsibility; <---
//I believe that I would need to declared this in order to use it in the schema
user = new userschema(req.body)
employment = new employmentObject(req.body)
userschema.js
var userSchema = mongoose.Schema({
full_name : String,
other_name : String,
last_name : String,
email : String
});
userSchema.pre('save', function (){
//obtain values from form field
var field1 = employmentDate;
var field2 = responsibility;
const employmentObject = this.model('employment-detail');
var emp_Date = employmentObject.employment_date;<-- I am calling what I declared earlier
var duties = employmentObject.responsibility;<-- I am calling what I declared earlier in express
**//when I declared above two lines it brings up the error **
**//Can't save() the same doc multiple times in parallel.**
employmentObjectins = new employmentObject({
'employment_date': emp_Date,
'responsibility' :duties
});
employmentObjectins.save(function (err){
if(err){
console.log(err+' error saving object');
}
else{
console.log('no error in saving object');
}
});
});
This is what i do in my projects
let userData = new UserModel(req.body);
let employmentData = new EmploymentModel(req.body);
This will save all the parameters from req.body matching the schema
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt-nodejs');
const crypto = require('crypto')
const Userschema = new Schema({
email:{
type:String,
unique:true,
lowercase:true
},
name:String,
password:String,
picture:String,
isSeller:{type:Boolean,default:false},
address:{
addr1:String,
addr2:String,
city:String,
state:String,
country:String,
postalCode:String
},
created:{type:Date,default:Date.now}
});
// this pre function do encryption before saving the password into database
Userschema.pre('save',async function(next){
var user =this;
console.log(user.password);
if (!user.isModified('password')) {
return next();
}
bcrypt.hash(user.password,null,null,(err,hash)=>{
if (err) {
return next(err);
}
user.password = hash;
next();
**this is my mistake I miss "next()"**
})
})

Saving twitter stream not properly saved in MongoDB using Mongoose

So I wanted to save the stream of data from Twitter Streaming API in MongoDB using Mongoose. Somehow it doesn't save all of the data and it only saves 1 document out of the infinite amount of data in the stream(that is not complete) when i run my code:
var mongoose = require('mongoose'),
TwitterStream = require('twitter-stream-api'),
fs = require('fs');
mongoose.connect('mongodb://localhost/insert_sample');
var keys = {
consumer_key : "",
consumer_secret : "",
token : "",
token_secret : ""
};
var Schema = mongoose.Schema;
// create a schema
var userSchema = new Schema({}, {"strict": false});
// 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;
var Twitter = new TwitterStream(keys, false);
Twitter.stream('statuses/filter', {
track: 'travel'
});
// create a new user called twitter
var Twitter = new User();
// call the built-in save method to save to the database
Twitter.save(function(err) {
if (err) throw err;
console.log('User saved successfully!');
});
Output of the command line: User saved successfully!
When I try to query in MongoDB shell using db.users.find(), the result is this:
{ "_id" : ObjectId("5a60a5558f4f1d21bcadd72b"), "__v" : 0 }
When it should be like:
{
"created_at": "Fri Aug 04 05:42:03 +0000 2017",
"id": 893346273255866400,
"id_str": "893346273255866368",
..........and soooo many more attributes }
EDIT!!! Sorry I accidentally hit enter and posted it without the other needed things to be clear. My bad.
You are overwriting your Twitter Variable and saving the user data empty object.
// create a new user called twitter
var Twitter = new User();
// call the built-in save method to save to the database
Twitter.save(function(err) {
if (err) throw err;
Once you create a stream you need to listen for data event and use that data to save in your database.
Remove above lines and use something like;
// listen for data from stream
Twitter.on('data', function (obj) {
var data = obj.toString('utf8');
console.log(data);
var TwitterData = new User(data); // create object
TwitterData.save(); // save data to DB
});
Hope it Helps!

Issues while trying to implement multi tenant system using node.js with mongodb

We have different clients and the idea is to keep their data separate from each other in the same application. We are using node.js with mongodb and mongoose is being used for querying.
This is 'index.js' file in models directory
var mongoose = require('mongoose');
var fs = require('fs');
var connectionUrl = 'mongodbserverlink/';
var companies = [{ db: 'comp1_db', comp_id: 'com1' }, { db: 'com2_db', comp_id: 'com2' }, { db: 'com3_db', compa_id: 'com3'}];
var connections = {};
var models = {};
fs.readdirSync(__dirname)
.forEach(function (file) {
var Schema = file.split('.js')[0];
if (Schema === 'index') return;
models[Schema] = require('./' + Schema);
});
companies.forEach(function (company) {
var conn = mongoose.createConnection(connectionUrl + company.db);
connections[company.company_id] = {};
Object.keys(models).forEach(function (Schema) {
connections[company.company_id][Schema] = conn.model(Schema, models[Schema]);
});
conn.on('error', console.error.bind(console, company.db + ' connection error in mongodb in the first step!'));
conn.once('open', function() {
console.log(company.db + " mongodb connected");
});
});
module.exports = connections;
Here the connection is being made with different databases. The models directory has this index file.
Now in the controller where application logic is being done, this is what we are doing.
var models = require('../models');
var comp_id = req.body.comp_id;
db.collectionname.find...(This is not the syntax for find, I just cut it short to keep it simple) // -> this is not working now
when we tried logging models object this is what we got
models object is: {"com1":{},"com2":{},"com3":{}}
and only db when logged gives {}
We are facing issues in grasping the complete work... it is because the person who wrote the major chunk is not with us and there is no documentation.
What are we doing wrong here?
It looks like you already have your models exported from the index file. So, in the controller you can do a var models = require('index');. From the connections object, you may be able to retrieve the corresponding model: var companyModel = models[comp_id];.
Hope it helps.

How do I convert a regular JSON object into a Mongo document using Mongoose?

I have a JSON Object called parsedSong that I want to convert into a Mongo document using Mongoose.
var newSong = new Song(parsedSong);
However, this only provides me with a new document that only has an id attribute. How can I make a conversion that doesn't cut my data from parsedSong?
I assumed you have defined these variables in schema. Then you can make something like this:
var bestSong = {
artist: "Seether",
song: "Careless Whisper"
};
var song = new Song(bestSong);
song.save(function(err) {
if(err) throw err;
console.log('saved');
});
And now this song should be in database.

Making multiple requests to api at once and display result to the template view engine

I just started learning with API. And I'm stumbling upon this problem.
MY GOAL: I would love to make two separate calls to marvel API at the same time. The first call will get all the data about the character and its id then I bundle them together inside a variable and save it in the database. Now, the second call will get all the comics data and these data will be embeded to the character object that was created during the first call. Now that I have this complete character variable. I can then send it to the view engine. But I do not know how to do it. Is there a simpler way to tackle this problem ?? Can you guys please let me know what I am doing wrong here...
//Mongoose model set up for Thumbnail > path, and extension
var Schema = mongoose.Schema;
var thumbnailSchema = new Schema({
path: "String",
extension: "String"
});
var thumbnailPath = mongoose.model('thumbnailPath', thumbnailSchema);
//Mongoose model set up for Comics
var Schema = mongoose.Schema;
var comicsSchema = new Schema({
title: "String",
imagePath: [thumbnailSchema]
});
var Comics = mongoose.model('Comics', comicsSchema);
//Mongoose model set up for Character
var Schema = mongoose.Schema;
var characterSchema = new Schema({
id: "Number",
name: "String",
description: "String",
imagePath: [thumbnailSchema],
comicsPath: [comicsSchema]
});
var Character = mongoose.model('Character', characterSchema);
//Create POST
app.post('/', function(request,response){
var characterData = request.body.character;
var url = "https://gateway.marvel.com/v1/public/characters?name=" + characterData + "&ts=thor&apikey=PRIVATe"
Request(url,function(error,res,body){
var apiData = JSON.parse(body)
if(!error && res.statusCode == 200){
var newCharacter = Character ({
id: apiData.data.results[0].id,
name: apiData.data.results[0].name,
description: apiData.data.results[0].description
});
newCharacter.imagePath.push({
path: apiData.data.results[0].thumbnail.path,
extension: apiData.data.results[0].thumbnail.extension
});
} else {
var characterID = newCharacter.id
var comicsURL = "https://gateway.marvel.com/v1/public/characters/" + characterID + "/comics?limit=5&ts=thor&apikey=PRIVATE";
Request(comicsURL,function(error,res,body){
if(!error && res.statusCode == 200){
var comicsData = JSON.parse(body)
var newComics = Comics({
title: comicsData.data.results[0].title,
});
newComics.imagePath.push({
path: comicsData.data.results[0].thumbnail.path,
extension:comicsData.data.results[0].extension
});
newCharacter.imagePath.push({newComics})
console.log(newComics);
}
})
}
})
});
Everyone... I manage to take this one down by using a request-promise https://github.com/request/request-promise library. Now, with the searched character from the API as well as the comics front together. I can save it into a variable then take it to the database to store; that is happening in the background. With that finish, we can then hopefully pass it over successfully (will see) to the template engine to view. For future references......
code code2

Categories