Node js and mongoose schema date.now code not working properly - node.js

I have created this schema for user registration:
let userSchema = new mongoose.Schema({
lname: String,
fname: String,
username: String,
email: String,
password: String,
registrationDate: {
type: Date,
default: Date.now()
},
referedBy: {
type: String,
default: ''
},
referalEnd: {
type: Date,
default: Date.now() + 5*365*24*60*60*1000
},
userRefererId: {
type: String,
default: uniqid()
}
});
As you can see, there is a Date.now function and uniqid function in the schema.
Those functions can be used approximately once every 5 minutes,
because if I create two users a few seconds apart, it generates the same uniqid and shows the same date.

Remove the () from Date.now() and just call Date.now.

I've run into this before, the schema is generated at deployment / start time and not regenerated on each new creation hence why the time is always the same. Its better to generate the date / time outside the new Model().save() call.

let userSchema = new mongoose.Schema({
lname: String,
fname:String,
username: String,
email: String,
password: String,
registrationDate: {
type: Date,
default: function(){return Date.now()}
},
referedBy: {
type:String,
default: ''
},
referalEnd: {
type: Date,
default: function(){ return Date.now() + 5*365*24*60*60*1000}
},
userRefererId: {
type:String,
default: uniqid()
}
});

Related

Updating Field in a Nested Subdocument MongoDB

I'm trying to update the IsActive flag inside the function object, however, it is deeply nested inside the Companies and Factories Objects. Trying to use $ is no use, as it does not work with deeply nested subdocuments. Has anyone found a way to work with this???I expect the IsActive flag to be modified, as right now it can only be reached. I've tried:
$$
List item
Placing the $ at various points i.e. Factories.Functions.$.IsActive
-Concatenating in functionIds
{function deleteFunction(companyId, factoryId, functionId) {
return Companies.update({
"CompanyId": companyId,
"Factories.FactoryId": factoryId,
"Factories.Functions.FunctionId": functionId,
}, {"$set": {"Factories.$.Functions.IsActive": false}}
).then(function (result) {
console.log("Reached", result);
return result
}).catch(function (err) {
logger.log(err);
});
}}
let functionsSchema = new mongoose.Schema({
FunctionId: Number,
Name: String,
ADGroup: String,
IsActive: Boolean,
DateCreated: {
type: Date,
default: Date.now
},
DateModified: {
type: Date,
default: Date.now
}
});
let factorySchema = new mongoose.Schema({
FactoryId: Number,
Name: String,
ADGroup: String,
IsActive: Boolean,
DateCreated: {
type: Date,
default: Date.now
},
DateModified: {
type: Date,
default: Date.now
},
Functions: [functionsSchema]
});
let companySchema = new mongoose.Schema({
CompanyId: Number,
Name: String,
IsActive: Boolean,
DateCreated: {
type: Date,
default: Date.now
},
DateModified: {
type: Date,
default: Date.now
},
Employees: [employeeSchema],
Factories: [factorySchema]
});

How to update mongoose schema?

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

Is there any thing similar to mongo.model(); in DynamoDB...?

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.

Missing subdocument while trying to fetch a document

Issue:
I am creating an accounts table with the schema as shown below. I have just one account document for a user in a mongo server that's running in my localhost. After defining the schema and adding a single account document, I wrote an endpoint to query and fetch that document (Model.find(id: '12345')) using the id key. The resulting JSON document has all the data except the subdocument named accRef as show in the Schema below. When I try the same find query using the Mongo Shell, I get the results perfectly. I've been trying to find what's causing this for almost an entire day now, without making much headway. Any help would be highly appreciated.
I started with an empty schema and added each field one by one, starting with the id attribute and fire the find query. Every single time, I get all the 75+ elements and subdocuments, but the moment I add the accRef subdoc to my schema, this piece of info disappears from the result.
Is there a limitation to the number of subdocuments that can be defined in mongoose's schema?
Also, I cannot seem to insert/save any new account object using the same schema as shown below. However, I can perform this insert/save operation using the very same JSON object, using a client like MongoChef.
Here's my JS module where I've defined my schema:
import mongoose from 'mongoose';
mongoose.connect('mongodb://localhost:27017/accounts');
const Schema = mongoose.Schema;
const accountsSchema = new Schema({
_id: Schema.ObjectId,
id: String,
uuid: String,
firstName: String,
lastName: String,
contactNumber: Number,
dob: Date,
email: String,
originalEmail: {type: String, index: true},
password: String,
socialMedia: {
facebook: {
id: String,
email: String,
token: String
}
},
domainInfo: {
country: String,
currency: String,
lang: String,
domain: String
},
profile: {
type: Number,
id: Number,
points: Number,
accumulated: Number
},
perks: {
id: Number,
type: Number
},
address: {
address: String,
postalCode: String
},
paymentInfo: {
cardNumber: String,
isValidCard: Number,
paypal: {
email: String
},
bank: {
bankName: String,
bankNumber: String,
accontId: Number,
accountHolderName: String,
bankBranchCode: String,
paymentTypeId: Number
},
dateCreated: {type: Date, default: Date.now},
dateModified: {type: Date, default: Date.now},
createdAt: {type: Date, default: Date.now},
updatedAt: {type: Date, default: Date.now}
},
metadata: {
timezone: String,
ipAddress: String,
signupMeta: String,
clientUserAgent: String,
signupUrl: String
},
accRef: {
type: String,
code: String,
url: String
},
key: String,
parentId: String,
type: String,
utm: String,
bounced: Number,
status: Number,
isPoints: Number,
isAdmin: String,
dateTutorialCompleted: {type: Date, default: Date.now},
dateCreated: {type: Date, default: Date.now},
dateModified: {type: Date, default: Date.now},
dateAccessed: {type: Date, default: Date.now},
dateVerified: {type: Date, default: Date.now},
datePurchased: Date,
createdAt: {type: Date, default: Date.now},
updatedAt: {type: Date, default: Date.now}
});
const Account = mongoose.model('Account', accountsSchema);
export default Account;
The function in the service class that fires the mongo query:
import Account from '../../models/mongo';
const getAccountById = (accountId) => {
return Account.find({id: accountId})
.then(response => {
if(response.length === 0) {
throw new Error("Account Not Found");
}
console.log(response);
return response;
})
.catch(error => {
throw new Error(error.message);
});
};
Mongoose Version tried with: 4.7.7 and 4.7.8 (tried both)
MongoDB Version tried with: 3.2 and 3.4 (tried both)
Node Version: 7.4.0

Mongoose: find all referenced documents

I have 2 schemas:
var pollSchema = new mongoose.Schema({
title: String,
created: {
type: Date, default: Date.now
},
options: [{
label: String,
count: {
type: Number, default: 0
},
backgroundColor: {
type: String, default: '#fff'
}
}],
author:{
id:{
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
}
});
var userSchema = new Schema({
username: {type: String, unique:true},
email: {type: String, unique:true, lowercase: true},
password: String
});
Now each poll will store data of it's author.
Questions:
How can I redesign my schemas - so I will be able to find all the polls belong to particular user?
Or should I leave the schemas the same and find another approach?
you can still find all the polls belonging to a particular user . You have the author.id for that.
Also you can keep an array as var userSchema = new Schema({
username: {type: String, unique:true},
email: {type: String, unique:true, lowercase: true},
password: String,
polls: []
});
And every time a user polls, push the userId inside the polls array, which you can later populate or get the count.

Resources