I want to create Dynamo db tables in node.js script.
In short i want dynamo-db code equivalent to following:
var mongo = require('mongoose');
var MongoDB = mongo.connect('mongodb://localhost:27017/test').connection;
MongoDB.on('error', function(err) { console.log(err.message); });
MongoDB.once('open', function() {
console.log("DynamoDB connection open");
});
var userschema = mongo.Schema({
name: String,
nickname: {type: String,default: ''},
email: String,
phone: String,
type: String,
port : String,
deviceRegId: {type: String,default: ''},
assignFlag: Number,
created: {type: Date,default: Date.now} ,
lastmsg : {type: String,default: ''} ,
lasttime : {type: Date,default: Date.now} ,
loginStatus : {type: Boolean,default: false} ,
isOnline : {type: Boolean,default: false} ,
chats: [{
from: String,
msgfrom: Number,
name: String,
msg: String,
date: {type: Date, default: Date.now},
flag: Number
}]
});
var agent = mongo.model('naveen', userschema);
exports.mongo = mongo;
exports.agent = agent;
I am trying to search similar Dynamo function, but could not find any. Any help would be of great use.
Here is the sample code to create the table if not present and create an item on it with default values.
Please note that you can't have empty value for an attribute on DynamoDB. For example, the nickname can't be set as empty string by default.
For any attribute, if you set an empty value and try to insert the data, DynamoDB will throw a validation exception.
So, default can't be empty string.
Code:-
var dynamoose = require('dynamoose');
dynamoose.AWS.config.update({
accessKeyId: 'AKID',
secretAccessKey: 'SECRET',
region: 'us-east-1'
});
dynamoose.local();
var Schema = dynamoose.Schema;
var userSchema = new Schema({
name: {
type: String,
hashKey: true
},
nickname: String,
email: String,
phone: String,
type: String,
port: String,
deviceRegId: String,
assignFlag: Number,
created: { type: Date, default: Date.now },
lastmsg: { type: String },
lasttime: { type: Date, default: Date.now },
loginStatus: { type: Boolean, default: false },
isOnline: { type: Boolean, default: false },
chats: [{
from: String,
msgfrom: Number,
name: String,
msg: String,
date: { type: Date, default: Date.now },
flag: Number
}]
},
{
throughput: { read: 15, write: 5 }
});
var Table = dynamoose.Table;
var UserDetails = dynamoose.model('UserDetails', userSchema);
var user1 = new UserDetails({ name: 'John' });
user1.save(function (err) {
if (err) { return console.log(err); }
console.log('Added a new item');
});
Sample item created:-
Date value is stored as Number.
Related
This is my schema
var UserSchema = new Schema({
username: String,
email: String,
password: String,
company: String,
contact: Number,
country: String,
isLoggedIn: Boolean,
createdOn: { type: Date, default: Date.now },
ads: [{ type: Schema.Types.ObjectId, ref: 'Ad' }],
notification: {
counter: {type: Number, default: 0},
notidata: [{ itemdate: { type: Date, default: Date.now }, data: {type: String}}]
}
});
var User = module.exports = mongoose.model('User', UserSchema);
I am trying to push data into the notification.notidata.data by the following way and it seems to not be working.
User.findByIdAndUpdate(newuser.id, {
'$set': {
'notification.$.counter': '1',
'notification.$.notidata.data': 'two updated'
}
}, function(err, post) {
if (err) {
console.log(err)
} else {
console.log(post);
}
});
It seems like I am not getting how to access that sub-documented field called data.
Try the $set as:
'$set': {
'notification.counter': '1',
'notification.notidata.0.data': 'two updated'
}
I have a user model schema, a work model schema, and a critique model schema. The relationship between these schema's is a user can submit many works (like blog posts), and can comment/review (which we call critiques) other people's posts (works).
So when a user submits a critique (think of it like a review), this is my post route. I find the work by the id, then create a new critique model object, and pass that to the .create() mongoose function. All goes seemingly well until I hit the foundWork.critiques.push(createdCritique) line. the console log errors out saying:
BulkWriteError: E11000 duplicate key error collection: zapper.critiques index: username_1 dup key: { : null }
Obviously, it is saying that there are two username keys in the objects and they're conflicting with each other, but I'm not familiar enough with this to find the root of the issue and fix it in the mongoose models. The models are below. If anyone could help, that'd be greatly appreciated.
// post route for getting the review
router.post('/:id', isLoggedIn, function(req, res) {
Work.findById(req.params.id, function(err, foundWork) {
if (err) {
console.log(err);
} else {
// create a new critique
var newCritique = new Critique ({
reviewerName: {
id: req.user._id,
username: req.user.username
},
work: {
id: foundWork._id,
title: foundWork.title
},
critique : req.body.critique,
date: Date.now(),
rating: 0
});
// save new critique to db
Critique.create(newCritique, function(err, createdCritique) {
if (err) {
console.log(err)
} else {
console.log("Created critique is ");
console.log(createdCritique);
// push the new critique into array of critiques of the work
foundWork.critiques.push(createdCritique);
// save to db
foundWork.save();
}
});
}
});
User model:
var mongoose = require('mongoose');
var passportLocalMongoose = require('passport-local-mongoose');
var UserSchema = new mongoose.Schema({
firstname: String,
lastname: String,
username: String,
password: String,
email: String,
zip: String,
bio: {
type: String,
default: ''
},
influences: {
type: String,
default: ''
},
favBooks: {
type: String,
default: ''
},
notWriting: {
type: String,
default: ''
},
favHero: {
type: String,
default: ''
},
favVillain: {
type: String,
default: ''
},
works: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Work'
}
],
critiques: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Critique'
}
],
friends: [
{
friendId: String,
friendName : String,
friendPic: String
}
],
friendRequests: [
{
sendingFriendId: String,
sendingFriendName : String,
sendingFriendPic: String
}
],
createdDate: {
type: Date,
default: Date.now
},
lastLogin: {
type: Date,
default: Date.now
}
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);
Work model:
var mongoose = require('mongoose');
var WorkSchema = new mongoose.Schema({
title: String,
genre: String,
workType: String,
length: Number,
ageRange: String,
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
},
manuscriptText: String,
critiques: [
{
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "Critique"
}
}
],
ratingNumber: [Number],
ratingSum: {
type: Number,
default: 0
},
date: {
type: Date,
default: Date.now
},
isPublic: {
type: Boolean,
default: true
}
});
module.exports = mongoose.model("Work", WorkSchema);
Critique model:
var mongoose = require('mongoose');
var passportLocalMongoose = require('passport-local-mongoose');
var CritiqueSchema = new mongoose.Schema({
reviewerName: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
},
work: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "Work"
},
title: String
},
critique: String,
date: {
type: Date,
default: Date.now
},
rating: [Number]
});
CritiqueSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("Critique", CritiqueSchema);
When you create a unique index in MongoDB, the default behavior is that it will index null values also.
This means if you have a document in your collection with a username of null, you can not add another one with a username of null.
What you need is a sparse index which only indexes actual values (and ignores documents with null for that field).
Check this link It shows how to create a sparse index vs "normal" one in mongoose (index: true, vs spare: true). Most of the time you would want sparse indexes.
I want to make the "address" property "null" or "undefined" if I haven't initialized it in mongoose. I have tried to initialize it to a null value but didn't work.
var userSchema = new Schema({
name: { type: String, default: null },
address: {
number: { type: String, default: null },
route: { type: String, default: null },
areaInner: { type: String, default: null },
areaOuter: { type: String, default: null },
country: { type: String, default: null }
}
},{timestamps:true});
var User = mongoose.model('users', userSchema);
var newUser = User({
name: name,
address:null
});
newUser.save();
You have to define an other schema for "address":
var addressSchema = new Schema({
number: {type: String, default: null},
...
});
var userSchema = new Schema({
name: {type: String, default: null},
address: {type: addressSchema, default: null}
});
I'm completely new to the NoSQL world and it's been difficult to wrap my mind around it. This week I was learning MongoDB (Mongoose) with Node.js and here is my current schema:
var eventDataSchema = new Schema({
_id : Number,
notes : {type: String, required: true},
start_date : {type: Date, required: true},
end_date : {type: Date, required: true},
}, {
id : false,
collection : 'event-data'
});
eventDataSchema.plugin(AutoIncrement);
var EventData = mongoose.model('EventData', eventDataSchema);
Now that this is working, I would like to add a user and password and have access to have personal access to EventData.
Also... later if I want to send a JSON of only the eventData, but not the user to my javascript, how would I do that?
The way I am currently sending my eventData to my js in this format:
router.get('/data', function(req, res){
EventData.find({}, function(err, data){
if (err) {
console.error('Error occured');
}
res.send(data);
});
});
Thanks again
As i can understand you want to add events key in your schema. Then your schema will be like that:
var userSchema = new Schema({
user: { type: String, required: true, trim: true },
password: { type: String, required: true, trim: true },
events: [{
notes: { type: String,required: true, trim: true },
start_date: { type: Date,required: true },
end_date: { type: Date,required: true }
}]
}
userSchema.plugin(AutoIncrement);
var userSchema = mongoose.model('userSchema', userSchema);
});
If the above code is not working then you can create two schema,one for user and other for eventData, and can populate your eventData in userSchema.
so your code will be like that:
userSchema.js:
var userSchema = new Schema({
user: { type: String, required: true, trim: true },
password: { type: String, required: true, trim: true },
events: {type: mongoose.Schema.Types.ObjectId, ref: 'EventData' }
userSchema.plugin(AutoIncrement);
module.exports = mongoose.model('userSchema', userSchema);
});
And your eventDataSchema will be:
eventSchema.js:
var eventDataSchema = new Schema({
notes: { type: 'string',required: true, trim: true },
start_date: { type: Date,required: true },
end_date: { type: Date,required: true }
}
eventDataSchema.plugin(AutoIncrement);
module.exports = mongoose.model('EventData', eventDataSchema);
});
and then you can get the result like that:
index.js:
var eventSchema = require('./eventSchema');
var userSchema = require('./userSchema');
var populate = [{
path: 'events',
model: 'EventData',
select: '_id notes start_dat end_date'
}];
var find = function (query) {
return userSchema.find(query).populate(populate).exec();
}
console.log(find());
Result:
{
_id:cfgvhbjnkmkdcfxghgjklxnmbxhdhjxjhjhgx,
user: John Doe,
password: 123,
events: [ { _id: 1gfye56785g3ycgevhxeftx568765egcd,
notes: Event A,
start_date: 1/1/01,
end_date: 1/1/01
} ]
}
just started learning mongodb, currently i have this schema
var BlogSchema = new mongoose.Schema({
title: String,
image: String,
body: String,
created: {
type: Date,
default: Date.now
}});
and i wanted to update it to be like this, but currently its not working right now, when i checked it on the mongo console the schema is still the old one
var BlogSchema = new mongoose.Schema({
title: String,
image: String,
body: String,
created: {
type: Date,
default: Date.now
},
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
}
});
this is the best i've come up with after reading this post, but it throw me an error TypeError: Undefined type undefined at author.required Did you try nesting Schemas? You can only nest using refs or arrays.
var BlogSchema = new mongoose.Schema({
title: String,
image: String,
body: String,
created: {
type: Date,
default: Date.now
},
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: {
type: String,
required: true,
default: null
}
}
});
You can't use Schema like that instead just make another authorSchema and use it as array.
var mongoose = require('mongoose');
var authorSchema = new mongoose.Schema({
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: {
type: String,
required: true,
}
})
var BlogSchema = new mongoose.Schema({
title: String,
image: String,
body: String,
created: {
type: Date,
default: Date.now
},
author: [authorSchema]
})