Mongodb Save data with nodejs - angularjs

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

Related

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()
})
})

Embed the collections using mongodb

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!');
});

Get specific data in mongodb nodejs

i'm working with nodejs server using mongoDB. Now i have a sample data:
{
"_id": ObjectId("555f1c0c7f4b820758b439b0"),
"user": "Guest1",
"friend": [{
"myfriend": "Guest2",
"info": []
}, {
"myfriend": "Guest3",
"info": []
}]
}
Now i want to put all "myfriend" into array, like this:
var listfriend = ["Guest2","Guest3"];
So how can i do it ?
Thank for read :)
Try using the map() method as follows:
var listfriend = db.names.findOne(
{"user" : "Guest1"},
{"_id": 0, "friend": 1}
).friend.map(function(obj){
return obj.myfriend;
});
console.log(listfriend); // ["Guest2","Guest3"]
Did you want to use the aggregation framework?
var aggregateFriends = function( db, callback)
{
db.collection('test').aggregate(
[
{ $unwind: "$friend" },
{ $group: { _id: "$user", friends: {$push: "$friend.myfriend" } } }
]
).toArray( function( err, result ) {
console.log(result);
db.close();
} );
};
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert')
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/test';
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
aggregateFriends( db, function() { db.close(); });
} );

Inserting elements in array mongoose creates Object in NodeJS

I'm trying to insert documents in an array using Mongoose.
Here's the Schema:
var user = new mongo.Schema({
_id : Number,
devices:[
{
device_id : String,
type : String
}
]})
The update code in NodeJS looks like:
app.put('/user/update',function(req,res){
var obj = req.body;
users.update(
{'user.username' : obj.email},
{
'user.username' : obj.email,
'user.password' : obj.password,
'user.name.first' : obj.name,
'user.department' : obj.department,
'user.year' : obj.year,
'user.college' : obj.college,
'user.contact.phone': obj.contact,
'user.last_login' : obj.last_login,
$push:{
'devices': {
device_id: 'sadasd32u4je3bdjas',
type: 'Windows'
}
}
}, function(err){
if(err)
res.json({"foo": String(err)});
else
res.json({"foo": "Successfully Signed up!"});
});
}
);
But instead it inserts something like:
"devices": [
"[object Object]",
"[object Object]",
"[object Object]",
"[object Object]",
"[object Object]"
],
Where did I go wrong? Thanks again.
Use the findOneAndUpdate() method with the 'upsert' option set to true - this creates the object if it doesn't exist (defaults to false):
var obj = req.body;
var query = {'user.username': obj.email};
var doc = {
$set: {
'user.username': obj.email,
'user.password': obj.password,
'user.name.first': obj.name,
'user.department': obj.department,
'user.year': obj.year,
'user.college': obj.college,
'user.contact.phone': obj.contact,
'user.last_login': obj.last_login
},
$push: {
'devices': {
device_id: 'sadasd32u4je3bdjas',
type: 'Windows'
}
}
};
var options = {upsert: true};
users.findOneAndUpdate(query, doc, options, function(err){
if(err)
res.json({"foo": String(err)});
else
res.json({"foo": "Successfully Signed up!"});
});

Properties with default values in Mongoose schema are not persisting

I have the following schema I've written using Mongoose:
var querySchema = mongoose.Schema({
quoteId: { type: String, default: '' },
zipcode: { type: String, default: '' },
email: { type: String, default: '' },
type: {type: String, default: ''},
isEmailChecked: { type: Boolean, default: true },
});
I provide values for only 3 properties in the querySchema assuming that the result of the fields will take default values when a new instance of query object is persisted:
var query = {};
query.quoteId = "1414775421426";
query.email = "myself#somewhere.com";
query.type = "Foo";
But following document is what I see as the result in the collection:
{
"_id" : ObjectId("5453c27d0e4c3f2837071856"),
"email" : "myself#somewhere.com",
"type" : "Foo",
"quoteId" : "1414775421426",
"__v" : 0
}
Should isEmailChecked and zipcode not be assigned their default values when a new instance of query object is persisted to the MongoDB database?
Following is how I am persisting an instance of the query object using ExpressJS/NodeJS:
app.post('/api/queries', function (req, res) {
QuoteQuery.create({
quoteId: req.body.query.quoteId,
type: req.body.query.type,
zipcode: req.body.query.zipcode,
email: req.body.query.email,
isEmailChecked: req.body.query.isEmailChecked,
}, function (err, query) {
if (err) {
res.send(err);
}
res.json(query);
});
});
Could somebody help me understand that why I got the isEmailChecked and zipcode properties in the resulting document in the MongoDB database?
I am using NodeJS, AngularJS and ExpressJS in my application along with MongoDB.
When you set mongoose model field it not use default value.
As workaround you can use underscore to extend mongoose model object with keys which exists in your query object like this:
_.extend(dbQueryObject, query);
Here is complete example:
var mongoose = require('mongoose');
var querySchema = mongoose.Schema({
quoteId: { type: String, default: '' },
zipcode: { type: String, default: '' },
email: { type: String, default: '' },
type: {type: String, default: ''},
isEmailChecked: { type: Boolean, default: true }
});
var db = mongoose.createConnection('mongodb://localhost:27017/stackoverflow',
{ server: { auto_reconnect: true } },
function(err) {
var QuerySchema = db.model('test', querySchema);
var query = {};
query.quoteId = "1414775421426";
query.email = "myself#somewhere.com";
query.type = "Foo";
QuerySchema.create({
quoteId: query.quoteId,
type: query.type,
zipcode: query.zipcode,
email: query.email,
isEmailChecked: query.isEmailChecked
}, function (err, query) {
process.exit(0);
});
});
Here is what in db:
{
"_id" : ObjectId("5453ce3c9f7e0d13c52abf61"),
"type" : "Foo",
"email" : "myself#somewhere.com",
"quoteId" : "1414775421426",
"__v" : 0
}

Resources