I have a form on a page, I want a user to enter something in the form click submit, then make a request to MongoDB using the input of that form and render parts of that request onto a page, using nodejs, mongoose, and ejs
The schema of the collection has a field that always contains an object and I would like to search for a document in the collection that has a key that matches the input of the form.
The schema of the collection is
const ArrivalTimesSchema = new mongoose.Schema({
postcodeArrivalTimes: {
type: Object,
required: true,
},
workerId: {
type: String,
required: false
},
company: {
type: String,
required: true
},
})
And an example of postcodeArrivalTimes is
postcodeArrivalTimes = {AL95AT:"07:06", DL56EP:"13:06",AL14PL:"19:15"}
So in this case if someone input AL95AT into the input form I would want this document returned, how would I do that?
Not all documents would contain the key AL95AT but there could be multiple and I would like the last.
For this I think I can use .sort({ $natural: -1 }).limit(1) within a find() but I am not sure how to search for the keys within the object within the field.
Thank you for any help!!
CodePudding user response:
let input = "input" //inputKeyValue
let query = {};
query[input] = { $exists: true };
db.collection.find(query).sort({ $natural: -1 }).limit(1)