I was wondering if anyone could help me add a dynamic date to my database. The idea is I want to sort the database by people who have registered. So below I have a user schema of the values my database holds I have tried different things like adding a variable that holds a date object but no luck. I have tried searching around with no clear answer. Is there someone that can help me out?
var userSchema = new Schema({
firstName: {type: String, required: true, validate: nameValidator},
lastName: {type: String, required: true, validate: nameValidator},
addressOne: {type: String, required: true, validate: addressValidator},
addressTwo: {type: String, validate: addressValidator},
city: {type: String, required: true, validate: cityValidator},
state: {type: String, required: true, validate: stateValidator},
zipcode: {type: String, required: true, validate: zipValidator},
country: {type: String, required: true, validate: countryValidator},
});
You can specify date datatype using Date. All supported data types can be found here.
var userSchema = new Schema({
firstName: {
type: String,
required: true,
validate: nameValidator
},
lastName: {
type: String,
required: true,
validate: nameValidator
},
registrationDate: {
type: Date,
required: false,
default: Date.now
}
);
Above code will also give registrationDate as current time of saving userSchema by default.
Related
I am making the following mongoose schema and i want to make sure that no object has the same autherFirstName and autherLastName. object may have one in common but not both of them
const authorShcema = new mongoose.Schema({
autherFirstName: {type: String, minLength: 2, required: true},
autherLastName: {type: String, minLength: 2, required: true},
autjorDob: {type: Date, required: true},
authorImage: {type: String},
authorBooks: [{type: mongoose.Schema.Types.ObjectId, ref: "Book"}],
});
https://mongoosejs.com/docs/2.7.x/docs/indexes.html
Create a composite unique index
authorShcema.index({ autherFirstName: 1, autherLastName: 1 }, { unique: true });
I wanted to save the data in "messageSchema" which is sub document of chatSchema by checking the "receiver" of chatSchema and "username" of userSchema.
like pseudoCode:-
if(userSchema.username == "Rahul" && userSchema.chatSchema.receiver){
then save the data in chatSchema.message;
}
Here is my Schema:-
var messageSchema = mongoose.Schema({
messageId: {type: String, unique: true, required: true},
created: {type: Date, default: Date.now},
messageContent: String
});
var chatSchema = mongoose.Schema({
message: [messageSchema],
receiver: {type: String, required: true}
});
var userSchema = mongoose.Schema({
username: { type: String, unique: true, required: true },
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
token: { type: String, required: false },
conversations: [chatSchema]
});
please suggest what should be code to save the message data.
tried below one that didn't work.
User.findOneAndUpdate({username: "rahul", "conversations.receiver": data.receiver },{$push: {"conversations.message": message}});
I think you need to use $elemMatch instead of the dot notation for matching properties within an array. Try this:
User.findOneAndUpdate(
{
username: "rahul",
conversations: {
$elemMatch: { receiver: data.receiver }
}
},
// or whatever your update is
{$push: {"conversations.message": message}
})
I have a User document which has a Notes subdocument.
I'm using the following code to push new notes for the user with the given email address.
UserSchema.statics.addNotesToUser = function (email, notes, callback) {
return this.updateOne(
{'email': email},
{$push: {notes}},
callback
)
};
This is working fine, however it's ignoring my unique constraint on the NoteSchema. these are my schemas
const NoteSchema = new Schema({
_id: false,
id: {type: String, required: true, trim: true, unique: true},
content: {type: String, required: true, trim: true, lowercase: true},
added: {type: Date, default: Date.now},
used: {type: Date, default: Date.now},
book: {
name: {type: String, required: true}
}
});
const UserSchema = new Schema({
email: {type: String, required: true, trim: true, lowercase: true, unique: true},
notes: [NoteSchema]
});
I'm wondering how I can make sure that when pushing new notes to my user, I can validate if the ID of the notes is unique.
Thank you.
To achieve uniqueness constraint like functionality in subdocuments, hope that's OK.
let notesId = [];
notes.forEach(function(val,index){
notesId.push(val.id)
})
db.yourCollection.update(
{ 'email': email, 'NoteSchema.id': { '$ne': { $each: notesId } }},
{$push: {notes} },
callback)
I am pushing nested JSON data to database. This is how my schema looks like,
const mongoose = require('mongoose');
// original Schema
const dataSourceSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: { type: String, required: true, unique: true },
type: { type: String, required: true },
projectId: { type: mongoose.Schema.Types.ObjectId, ref: 'Project', required: true },
config:{type: String, required: true}
});
module.exports = mongoose.model('DataSource', dataSourceSchema);
I would like to pass the following json data to my dataSourceSchema,
{
“name”:”JdbcSourceConnector”,
"type" :"string",
“config”: {
“connector.class”:” io.confluent.connect.jdbc.JdbcSourceConnector”,
“tasks.max”:1,
“connection.url”:”<connection to connect to database along with username and password>”,
“mode”:”incrementing”,
“incrementing.column.name”:”<incrementing column name in table>”,
“topic.prefix”:”test-mysql-jdbc-”
}
}
But its not taking, gives casting error or ',' expected.
So i tried this,
const dataSourceSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: { type: String, required: true, unique: true },
type: { type: String, required: true },
projectId: { type: mongoose.Schema.Types.ObjectId, ref: 'Project', required: true },
config:{
connector.class:{ type: String, required: true },
tasks.max:{ type: String, required: true },
connection.url:{ type: String, required: true },
mode:{ type: String, required: true },
incrementing.column.name:{ type: String, required: true },
topic.prefix:{ type: String, required: true }
}
});
this Schema is also giving me errors, ',' expected.
If i pass just a string as i have mentioned in my original schema, the data gets stored in db.
but i want to pass the nested json data, please guide me in right direction.
I also tried stringify the data , its not working.
As I see it , the error lies in defining you schema with your second schema you came close to the answer. Change you schema as follows:
const dataSourceSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: { type: String, required: true, unique: true },
type: { type: String, required: true },
projectId: { type: mongoose.Schema.Types.ObjectId, ref: 'Project', required: true },
config:{
connectorClass:{ type: String, required: true },
tasksMax:{ type: String, required: true },
connectionUrl:{ type: String, required: true },
mode:{ type: String, required: true },
incrementingColumnName:{ type: String, required: true },
topicPrefix:{ type: String, required: true }
}
});
I have suggested the change as mongoose doesn't understand the dot notation in the key column of it's schema, hence you were receiving the error you have mentioned.
If you want to use the dot notation for some reason encapsulate the key in " and not in the special character as appearing in your code snippet.
P.s. - Don't forget to change the key names in your json
In my user document, I want to individually index email and username as unique fields, so that a duplicate is never entered.
The problem is all of the documentation I have found for multiple unique indexes is for "Compound Indexing", which appears to somehow tie the second index to the first. I don't want that.
All I want is for in my signup step 1 if a user submits an email that already exists for MongoDB to return an error that it already exists, and exact same for step 2, when they set their username.
So I want them indexed and unique separate from each other. I'm using this now and it is tieing the 2 together somehow which is not what I want:
const UserSchema = new mongoose.Schema({
email: {
type: String,
required: true,
trim: true
},
username: {
type: String,
required: false,
trim: true
}
})
UserSchema.index({
email: 1,
username: 1
}, {
unique: true
});
Mongoose doesn't have a built-in validation for unique fields. I recommend the package (with this you can use the unique validator on the email and username fields): mongoose-unique-validator. Extend your code with:
let uniqueValidator = require('mongoose-unique-validator');
email: {
type: String,
required: true,
trim: true,
unique: true,
index: true
},
username: {
type: String,
required: false,
trim: true,
unique: true,
index: true
}
UserSchema.plugin(uniqueValidator, {message: 'is already taken.'});
Add unique: true to each field's definition in the schema to create separate, unique indexes for those fields:
const UserSchema = new mongoose.Schema({
email: {
type: String,
required: true,
trim: true,
unique: true
},
username: {
type: String,
required: false,
trim: true,
unique: true
}
})
See the Indexes section on this page for the documentation.