how to add time field in mongoose schema - mongodb

I'm creating a medicine reminder web app, that will require the user to enter the data related to medicine and the time at which the reminder will be shown.
So is there any way to store the user input time in the mongodb, there is a type to store date, but couldn't find anything to store time.
This is the mongoose schema
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const medicineSchema = new Schema({
title: {
type: String,
required: true
},
count: {
type: Number,
required: true
},
about: {
type: String
},
time: {
type: TimeRanges,
required: true
}
}, { timestamps: true })
module.exports = mongoose.model('Medicine', medicineSchema)
I tried timeranges but it shows timeranges is not defined, and I don't think timeranges will store time input.
Taking user input through the form

I am using String SchemaType with Date() object.
// Set current date TimeStamp, eg: '1666512804163'
TimeStamp: new Date().getTime().toString()
// Display saved TimeStamp, eg: '23/10/2022'
new Date(parseInt(TimeStamp)).toLocaleDateString()

Related

Mongoose set default on field update if field is not present or null

I have a mongoose schema like this suppose:-
var mSchema = new Schema({
name: { type: String, required: true}
});
and have been using this schema for a year and now i want to add gender to it like this :-
var mSchema = new Schema({
name: { type: String, required: true},
gender: { type: String, default: 'Male' }
});
whenever there will be an update request i want this gender to automatically set Male as default but i found that default don't set on update request.
(Note: It's just an example not a real life scenario. i just want mongoose default work if field is not present or null)
Is there any way in which i can set default on the updation of document ?
If you are using a function like update(), then this is not directly possible as stated by this answer. Still, you can simply switch to a function like findOne() and use save(), which should do the same.
When upserting documents, you can also check out the setDefaultsOnInsert option: https://mongoosejs.com/docs/defaults.html#the-setdefaultsoninsert-option
const options = {
// Create a document if one isn't found. Required
// for `setDefaultsOnInsert`
upsert: true,
setDefaultsOnInsert: true
};
await XY.findOneAndUpdate(query, update, options);

Is possible to have multiple different types of refs for a single attribute in mongoose (mongodb)

I am using mongodb with mongoose. And i am wondering if it is possible to have multiple references for an object id attribute in a schema.
I have tried the code underneath and it did not work.
const Schema = new Schema({
refrens: {
type: ObjectId,
// this did not work
ref: [
"Post",
"Account"
],
required: true
}
});
I know it is possible to remove the ref attribute (field, key) and then all object ids are valid but i want certain object ids to be valid, the object ids of the Post and Account model.
const Schema = new Schema({
refrens: {
// This will allow all different types of object ids to be the value
type: ObjectId,
required: true
}
});
Look like refPath is what you need. You can do something like this:
const Schema = new Schema({
refrens: {
type: ObjectId,
refPath: 'onModel',
required: true
},
onModel: {
type: String,
required: true,
enum: ['Post', 'Account']
}
});

What's up with mongoose date/timestamps?

I've a problem. I've been trying 2 different approaches to get correct date after an item is added to the collection.
1. new Date()
2. Date.now()
Both examples has the same issue. Only first added document has correct date. The next one has exactly the same date. Why the date is not changing?
Here's my collection:
const commentSchema = new Schema({
author: {
type: Schema.Types.ObjectId,
ref: 'user'
},
addDate: {
type: Date,
default: Date.now()
},
content: String,
answers: [commentReplies],
articleID: {
type: Schema.Types.ObjectId,
ref: 'article'
}
});
My insertion code:
app.post('/api/comments/addComment', async (req, res) => {
const author = req.body.author,
content = req.body.content,
articleID = req.body.articleID;
const comment = await new Comment({
author, content, articleID
}).save().catch(err => {
console.log(err);
})
res.send();
})
Because doing that way mongoose use the date at the time the schema is created: it execute the Date.now() function and use the value as the default for every document.
Probably the better way to do it is to use a save hook and set the date programmatically in the hook.

MongoDB/Mongoose querying subdocuments and indexing

Ok, so I am new to MongoDB and the world of document based databases. I have stored in MongoDB a collection of profiles which has two subdocuments; 'Interest' and 'Country'. Below is schema information:
var Country = new mongoose.Schema({
name: String,
countryCode: String
});
var Interest = new mongoose.Schema({
label: {
type: String
}
});
var Profile = connection.model('profile', {
uid: {
type: String,
unique: true,
sparse: true
},
username: String
country: Country,
interests: [Interest],
member_since: Date
});
Let's say I want to be able to run a fast and efficient query such that I can select all of the users interested in 'music' and whose countryCode is 'AU' but done in an efficient way that doesn't scan all documents (I'm guessing I need an index?), how can I do this? Below is a sample profile as it appears in Compass:
_id:59d17efa3ed3a453e2b865f9
username:"Rudolph"
country:Object
name: "Australia"
countryCode:"AU"
_id:59d17efa3ed3a453e2b865fa
__v:0
interests:Object
label:Array
0:"music"
1:"film"
2:"dance"
member_since:2017-10-01 19:49:14.565

tuples (arrays) as attributes in mongoose.js

MongoDB, and mongoose.js specifically, allows tuples as attributes. For instance, the MongoDB documentation has this example where the attribute comments is itself an array of objects with the attributes [{body: String, date: Date}]. Yay!
var blogSchema = new Schema({
title: String,
author: String,
body: String,
comments: [{ body: String, date: Date }],
date: { type: Date, default: Date.now },
hidden: Boolean,
meta: {
votes: Number,
favs: Number
}
})
Now when i persist that to MongoDB, not only does each instance of blogSchema get its own value for _id (e.g. 502efea0db22660000000002) but each individual value of comment gets its own _id field.
For the most part I don't care, but in my app the analog to comments may have thousands of values. Each of which gets its own huge value of _id.
Can I prevent that? I'll never need to refer to them individually. Or should I learn to stop worrying and love the unique identifier? I grew up programming the Vic20 and TRS80 as a kid, so may be overly paranoid about wasting memory/storage.
The _id can be disabled by setting the noId schema option to true. To pass the option you need to pass an instance of schema instead of using the object literal:
// instead of this...
comments: [{ body: String, date: Date }]
// do this...
var commentSchema = new Schema({ body: String, date: Date }, { noId: true });
var blogSchema = new Schema({
..
comments: [commentSchema]
})