Embed the collections using mongodb - angularjs

I am just start using mongodb and nodejs. I know that mongodb does not supports joins.I simply insert the data in mongodb and my documents looks:
{
"_id": ObjectId("564dacf84d52785c1d8b4567"),
"content": "This blog created by karanSofat",
"html": "<p>This blog created by karanSofat</p>\n",
}
Now user comments on this post. it should be like this:
{
"_id": ObjectId("564dacf84d52785c1d8b4567"),
"comments": [
{
"name": "sumit",
"email": "sumit#ggi.net",
"comment": "this is also well for me",
"posted_at": ISODate("2015-11-19T11:06:27.172Z")
}
],
"content"▼: "This blog created by karanSofat",
"html": "<p>This blog created by karanSofat</p>\n",
}
Here is my models,
//post model
// grab the mongoose module
var mongoose = require('mongoose');
// define our nerd model
// module.exports allows us to pass this to other files when it is called
module.exports = mongoose.model('post', {
content : {type : String, default: ''},
html : {type : String, default: ''}
});
//comment model
var mongoose = require('mongoos
module.exports = mongoose.model('comment', {
name : {type : String, default: ''},
email : {type : String, default: ''},
comment : {type : String, default: ''},
posted_at : {type : date, default: ''}
});
My Problem is that I don't know on which way I insert comments data using nodejs and my document will embed.
Here is my code:
app.post('/comments/:id', function(req, res) {
var Comment = require("../app/models/comments");//comment Model
var blog = require("../app/models/blog");//blog model
var id = req.params.id; //postId
var comments = JSON.parse(JSON.stringify(req.body)); //commentdata
//code Should be here
res.json({data:id,data2:input});
});
Please help

Karan,
Let's assume you have the following schema:
var Comments = new Schema({
name: String,
email: String,
comment: String,
, posted_at: Date
});
var BlogPost = new Schema({
content : String,
html : String,
comments : [Comments],
});
mongoose.model('BlogPost', BlogPost);
You can add an embed document to an array as such:
// retrieve my model
var BlogPost = mongoose.model('BlogPost');
// create a blog post
var post = new BlogPost();
// create a comment
post.comments.push({
"name": "sumit",
"email": "sumit#ggi.net",
"comment": "this is also well for me",
"posted_at": ISODate("2015-11-19T11:06:27.172Z")
});
post.save(function (err) {
if (!err) console.log('Success!');
});

Related

mongoose + nodejs push array to database

I'm new to NodeJS + Mongoose and having trouble pushing an array to my database via mongoose.
I have the following schema:
const StudentSchema = mongoose.Schema({
name: {
type: String
},
quizzes: [{
quiz: String,
answers: []
}]
});
What I'm trying to do is have an array of quiz objects in which the quiz number is shown and the array of answers for that particular quiz.
When I create a new user, the student object looks like this in mongoose:
{
"_id" : ObjectId(id here),
"name" : "John",
"quizzes" : [ ],
"__v" : 0
}
The function I'm using to update the quiz array:
module.exports.addQuiz = function(student_id, answers, callback){
Student.findByIdAndUpdate(
student_id,
{$push: {"quizzes": {answers: answers}}},
{safe: true, upsert: true},
function(err, model) {
console.log(err);
}
);
}
And this is my route which calls the function whenever the endpoint is hit with a student_id, which will then be used to find the student and push to the array
router.post('/quiz/:student_id', (req, res, next) => {
var student_id = req.params.id;
var answers = req.body.answers;
Student.addQuiz(student_id, answers, (err, answers) => {
//error handling
})
});
I'm trying to test this by sending a post request to /quiz/:student_id with an id of a student in my database with the following JSON sent in the body:
[{
"quiz": "Quiz 1",
"answers": ["Answer 1", "Answer 2"]
}]
Although when I try this it ends up getting hung somewhere and the request never completes - I also get a "null" in the console.
Can anyone help me out? Thank you.

How to insert record automatically in mongodb (nodejs, express, mongoose)

I am working on a team-based project. I created a new collection with some records (inserted manually). Is there any script or code to insert these records automatically from within the code, so that my when my colleague will work they do not need to insert those records again.
Code:
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var ServiceCategoryTypeSchema = new Schema({
_id: {type: String},
name:String
}, {
collection:'service_category_type',
timestamps:{createdAt:'created_at', updatedAt:'updated_at'}
}
);
module.exports = {
getModel: function(db){
return db.model("ServiceCategoryType", ServiceCategoryTypeSchema)
},
schema:ServiceCategoryTypeSchema
};
This is the record, I am thinking to add automatically,
{
"_id" : "Inventory",
"name" : "Inventory"
}
{
"_id" : "Non-inventory",
"name" : "Non-inventory"
}
{
"_id" : "Service",
"name" : "Service"
}
When you have your model in, say, YourModel, then you should be able to save your data that you have in, say, yourData with something like this:
new YourModel(yourData).save(function (error, data) {
// handle errors, log success etc.
});
You can do it for as many pieces of data as you want.
When you populate the database with some data it may be a good idea to first check if the database is not populated yet.
Example
Here is a working example program that saves such data - I changed the database and collection names so that you won't mess with your real database when you run it:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var P = mongoose.Promise = require('bluebird');
mongoose.connect('mongodb://localhost/poptest');
var TestModel = mongoose.model('TestModel', new Schema({
_id: String,
name: String
}, {
collection: 'testcollection',
timestamps: {createdAt: 'created_at', updatedAt: 'updated_at'}
}
));
var sampleData = [
{_id: "Inventory", name: "Inventory"},
{_id: "Non-inventory", name: "Non-inventory"},
{_id: "Service", name: "Service"}
];
P.all(sampleData.map(i => new TestModel(i).save()))
.then(() => console.log('Data saved'))
.catch((err) => console.log('Error: ' + err))
.finally(process.exit);
You need to install mongoose and bluebird for it to work:
npm i mongoose bluebird
It creates 3 documents in the poptest database on localhost. You can verify it by running:
mongo poptest
and querying the testcollection collection:
db.testcollection.find();
You should get something like:
> db.testcollection.find().pretty();
{
"_id" : "Inventory",
"updated_at" : ISODate("2016-09-14T16:13:37.374Z"),
"created_at" : ISODate("2016-09-14T16:13:37.374Z"),
"name" : "Inventory",
"__v" : 0
}
{
"_id" : "Non-inventory",
"updated_at" : ISODate("2016-09-14T16:13:37.377Z"),
"created_at" : ISODate("2016-09-14T16:13:37.377Z"),
"name" : "Non-inventory",
"__v" : 0
}
{
"_id" : "Service",
"updated_at" : ISODate("2016-09-14T16:13:37.377Z"),
"created_at" : ISODate("2016-09-14T16:13:37.377Z"),
"name" : "Service",
"__v" : 0
}
This solution worked for me: https://github.com/Automattic/mongoose/issues/6326
'use strict'
const mongoose = require('mongoose')
const uri = 'mongodb://localhost/test'
const db = mongoose.createConnection(uri)
const Schema = mongoose.Schema
const testSchema = new Schema({
name: String,
age: Number
})
const Test = db.model('test', testSchema)
const test = new Test({ name: 'Billy', age: 31 })
db.once('connected', function (err) {
if (err) { return console.error(err) }
Test.create(test, function (err, doc) {
if (err) { return console.error(err) }
console.log(doc)
return db.close()
})
})

Mongoose doesn't create subdocument from JSON array

I'm trying to write a JSON object that contains both first-level data along with arrays into MongoDB.
What happens instead is all first-level data is stored, but anything contained in an array isn't. When logging the data the server receives, I see the entire object, which leads me to believe there's something wrong with my Mongoose code.
So for example if I send something like this:
issueId: "test1",
issueTitle: "testtest",
rows: [
{order:1,data: [object]},
{order:2,data: [object]},
]
Only the following gets stored:
issueId: "test1",
issueTitle: "testtest",
lastUpdated: Date,
I have the following model for Mongo:
//model.js
var mongoose = require('mongoose');
var model = mongoose.Schema({
issueId : String,
issueTitle : String,
lastUpdated : {type: Date, default : Date.now},
rows : [{
order : Number,
data : [
{
title : String,
text : String,
link : String,
}
]
}]
});
module.exports = mongoose.model('Model', model);
And the routing code, where I believe the problem likely is:
//routes.js
const mongoose = require('mongoose');
const Model = require('./model.js');
...
app.post('/api/data/update', function(req, res) {
let theData = req.body.dataToInsert;
console.log(JSON.stringify(theData,null,4));
Model.findOneAndUpdate(
{issueId : theData.issueId},
{theData},
{upsert: true},
function(err,doc){
if(err) throw err;
console.log(doc);
});
});
As well, here's the part of the Angular controller storing the data. I don't think there's any problem here.
pushToServer = function() {
$http.post('/api/data/update',{
dataToInsert : $scope.dataObject,
}).then(function successCallback(res){
console.log("all good", JSON.stringify(res,null,3));
}, function errorCallback(res){
console.log("arg" + res);
});
}
Look at the first question in the mongoose FAQ:
http://mongoosejs.com/docs/faq.html
Mongoose doesn't create getters/setters for array indexes; without them mongoose never gets notified of the change and so doesn't know to persist the new value. The work-around is to use MongooseArray#set available in Mongoose >= 3.2.0.
// query the document you want to update
// set the individual indexes you want to update
// save the document
doc.array.set(3, 'changed');
doc.save();
EDIT
I think this would work to update all of the rows. I'd be interested to know if it does work.
let rowQueries = [];
theData.rows.forEach(row => {
let query = Model.findOneAndUpdate({
issueId: theData.issueId,
'row._id': row._id
}, {
$set: {
'row.$': row
}
});
rowQueries.push(query.exec());
});
Promise.all(rowQueries).then(updatedDocs => {
// updated
});

MEAN Mongodb replace collection and create documents

So i have a schema like that:
var article = new mongoose.Schema({
title : String,
comments : [{
pe: mongoose.Schema.Types.ObjectId,
ref: 'Comment'
}]
});
and:
var comment = new mongoose.Schema({
created : Date,
text : String
});
now i have my small angular application, when i retrieve with my API and article i get something like:
{
title : "please help me"
comments : []
}
now on the front end I push some comments and the new object is:
{
title : "please help me"
comments : [{
text : "Now, go f**k yourself",
date : "1 January 1970 00:00:00 UTC."
}]
}
when i call the API and I update the document, I would like that mongo would Create the sub-object comments by himself, is there a way ?
Should it do it automatically ?
I would write a article schema this way (disclaimer: I haven't tried mongoose):
var article = new mongoose.Schema({
_id: String // or mongodb.ObjectId? I'm not sure.
title : String,
comments : [{
_id: String // this field is not nessesary
text: String,
date: String
}]
});
var comment = new mongoose.Schema({
created : Date, // created or date?
text : String
});
When you retrieve with you api, you'll get something like:
{
"_id": "ndrjgnd..fesf",
"title": "grdgrdgr",
comments: [ {"text": "hello", "created": "2016:...:"}, ... , ]
}
Then you can push new comments from front end:
{
"articleId": "ndrjgnd..fesf", // this is important.
"text": "balabala"
}
And update db: db.article.update( {_id: ariticleId}, {$push: newComment})

Mongodb Save data with nodejs

I am new in mongodb. I am simply insert the data using mongodb.My document looks:
{
"_id": ObjectId("5654085bf61deb761109d157"),
"address": "dsaddsadsad",
"email": "dsaddsadsad",
"name": "sadasdasdsad",
"__v": NumberInt(0)
}
My model looks:
// grab the mongoose module
var mongoose = require('mongoose');
// define our nerd model
// module.exports allows us to pass this to other files when it is called
module.exports = mongoose.model('users', {
name : {type : String, default: ''},
email : {type : String, default: ''},
address : {type : String, default: ''},
});
Now a user Comment on this.Then the document should be:
{
"comments": [
{
"uname": "arpit",
"uemail": "arpit#gmail.com",
"comment": "How can Make we this at good",
"posted_at": ISODate("2015-11-19T11:06:03.628Z")
},
{
"uname": "sumit",
"uemail": "sumit#ggi.net",
"comment": "this is also well for me",
"posted_at": ISODate("2015-11-19T11:06:27.172Z")
}
],
"_id": ObjectId("5654085bf61deb761109d157"),
"address": "dsaddsadsad",
"email": "dsaddsadsad",
"name": "sadasdasdsad",
"__v": NumberInt(0)
}
How can I make this document.My code is:
var Users = require("../app/models/users");
app.post('/comments/:id', function(req, res) {
var id = req.params.id; //coment id
var input = JSON.parse(JSON.stringify(req.body)); //comment data
//code should be here
});
Please help
/**users model*/
var mongoose = require('mongoose');
module.exports = mongoose.model('users', {
name : {type : String, default: ''},
email : {type : String, default: ''},
address : {type : String, default: ''},
comments: []
});
var Users = require("../app/models/users");
app.post('/comments/:id', function(req, res) {
var id = req.params.id; //coment id
var object = {}
for(var key in req.body){
object[key] = req.body[key];
}
Users
.findByIdAndUpdate(req.params.id, {$push: {"comments": object}})
.exec(function(error, result){
if(error){
console.log(error);
}
else{
console.log(result);
}
})
Test this:
Users.findByIdAndUpdate(id, {$push: {"comments":{
uname: req.body.the_uname,
uemail : req.body.the_uemail,
comment: req.body.the_comment,
posted_at: Date.now()
}
}
}).exec(function(error, res){});

Resources