VS Code Autocomplete suggestion taking up to 6s to display - visual-studio-code

I took the minimum of files for this scenario to works, which is an app.js and a folder with models/test.js
The app.js is empty and the models/test.js is a simple Mongoose model
const mongoose = require('mongoose');
let Schema = mongoose.Schema;
const testSchema = new Schema({
// General
language: String,
}, { timestamps: { createdAt: 'dates.created', updatedAt: 'dates.modified' } })
const Test = mongoose.model('Tests', testSchema);
module.exports = Test;
I found two scenarios that speed up the suggestion :
Commenting the module.exports = Test; in the model and going back to the empty app.js makes it instantaneous
Removing the node_modules folder
If I uncomment the module export or add any package (tested with 4 different npm package), the suggestion becomes again very slow
Observations :
The CPU also goes up by 15% when this happens
Disabling all extension didn't change the behaviour.
Reproduced on my PC and Macbook Pro.
I don't think I noticed this behaviour a few months ago.
Video showing everything (1min 8s)

Seemed to have been fixed with more recent updates

Related

Cannot overwrite mongoose model once compiled with Nextjs

Before you close this question, I have read several forums that have the same question as I have but my issue is way different. Even when Im not trying to do anything, even save a model, it still gives me an error of:
cannot overwrite "mongoose" model once compiled
I have a feeling there is something wrong with my schemas because when it was still simpler, it worked fine but as I tried to make it more complex it started to give me that error. Here is my mongoose code:
import mongoose from 'mongoose'
const flashcardItemSchema = new mongoose.Schema({
term: {
type:String,
required: true,
min:1
},
description: {
type:String,
required:true,
min:1
}
});
const FlashcardItem = mongoose.model("flashcardItem", flashcardItemSchema);
const flashcardSetSchema = new mongoose.Schema({
title: {
type: String,
min: 1,
},
flashcards:[flashcardItemSchema],
})
const FlashcardSet = mongoose.model('flashcardSet', flashcardSetSchema )
export {FlashcardItem, FlashcardSet}
I connect to my database when the server runs, so it doesn't disconnect from time to time.
UPDATE
I realized that I'm using nextjs builtin api, meaning the api directory is inside the page directory. I only get the error once the pages get recompiled.
So it turns out that the error came from nextjs trying to remake the model every render. There is an answer here: Mongoose/NextJS - Model is not defined / Cannot overwrite model once compiled
but I thought the code was too long and all that fixed mine was just a single line. When trying to save a model in nextjs, it should be written like this:
const modelName = mongoose.models.modelName || mongoose.model('modelName', flashcardSetSchema )

How do I fix this moment js bug in Mongoose?

I've created a posts model in Mongoose, that records all posts created by users.
const mongoose = require('mongoose');
const { Schema } = mongoose;
const moment = require('moment')
const postSchema = new Schema({
// Other fields in DB
timeCreated:{
type:String,
default: moment().valueOf()
}
});
const Posts = mongoose.model('Posts', postSchema);
module.exports = Posts
The exact part of the code I'm having problems with is this one here:
timeCreated:{
type:String,
default: moment().valueOf()
}
I'm using the timeCreated object to make time calculations in the front-end. So, when users create posts, the database will indicate that the posts were created at the same time, even if the posts where created hours apart.
See the database snapshot (emails and usernames are fake):
If you look closely, the timeCreated object carries the same string value in all 4 posts, regardless of the fact that the posts were created hours apart.
Is there something wrong with my code, or is this a Mongoose/Moment js bug?
I had a similar problem in my application, I did this to fix it.
I have lost the link where my problem was solved.
timeCreated:{
type:String,
default: () => moment().valueOf()
}
PS: I think you will be better of using default Javascript Date instead of moment, As they themselves are asking out to switch to a different alternative.
Read here.
Something like this.
timeCreated:{
type:String,
default: () => new Date()
}

Document not expiring in mongodb using mongoose

I am storing my refresh tokens in mongodb database. For testing purposes I want them to expire in 4 minutes. For some reason, this thing is not working for me.
const mongoose = require('mongoose');
let schema = new mongoose.Schema({
token: {
type: String,
required: true
},
username: {
type: String,
required: true
},
email: {
type: String,
required: true
},
});
schema.index({expireAt: 1}, {expiresAfterSeconds: 240}); //4 mins * 60 seconds
let model = mongoose.model('refresh_token', schema);
module.exports = model;
This is the complete code of my file. I am using this to create the refresh tokens. The item is persisting for an hour as of now. Please shed some light on my mistake.
OK, I solved the issue and it was a blunder from my side.
If you are using mongoose and doing the testing, you would most likely be changing the TTL expire time. I was changing it to see if it was working and for different testing purposes but once the document is created in the atlas, requesting a different TTL time won't overwrite the previous one. I changed the time from 30 months to 5 minutes and did a lot of fluctuation for testing purposes.
So keep this in mind that once the model is created, the TTL will be locked and you need to delete the collection and re-build it otherwise you have to change the TTL settings manually in the atlas(I didn't checked this out because my problem was solved with this only and I was in testing mode of my application). Also
thanks to wak786
for proposing to see the documentation again. It clicked when I was reading how indexing works.
My final refresh token file looks like this after I deleted the collection(actually renamed it).
const mongoose = require('mongoose');
let schema = new mongoose.Schema({
token: {
type: String,
required: true
},
username: {
type: String,
required: true
},
email: {
type: String,
required: true
},
createdAt: {
type: Date,
default: new Date()
}
});
schema.index({"createdAt": 1}, {expireAfterSeconds: 2592000}); //30days * 24hours * 60 minutes * 60 seconds
let model = mongoose.model('token', schema);
module.exports = model;
You are trying create index using following command.
schema.index({expireAt: 1}, {expiresAfterSeconds: 240});
But the field expireAt does not exist in your schema. And as per the mongo docs :-
If a document does not contain the indexed field, the document will not expire.
Reference:- https://docs.mongodb.com/manual/core/index-ttl/

Problem with FreeCodeCamp's "MongoDB and Mongoose - Create a Model" Challenge

I am doing FreeCodeCamp's "MongoDB and Mongoose - Create a Model" challenge. I have submitted by code. However, I am getting this error:
Creating an instance from a mongoose schema should succeed
Here are my codes:
let mongoose = require('mongoose')
mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true });
let personSchema = new mongoose.Schema({
name: {type: String, required: true},
age: Number,
favoriteFoods: [String]
});
let Person = mongoose.model('Person', personSchema);
Have I made any mistake?
Since you are submitting this code to FCC server, you don't need to connect to db by your own. They must be having connections already made to db. You just have to provide the right implementation of Person model. IMO Since you had that line in your submission, code was breaking at that line and subsequent lines were not getting executed. Hence you were getting this error. Creating an instance from a mongoose schema should succeed
Try this -
let mongoose = require('mongoose');
let Schema = mongoose.Schema;
let personSchema = new Schema({
name: {type: String, required: true},
age: Number,
favoriteFoods: [String]
});
let Person = mongoose.model('Person', personSchema);
The following code worked for me after trying many different things suggested on different posts/blogs on the Internet.
require('dotenv').config();
//To-Do # 1: Install & Set up mongoose */
const mongoose = require('mongoose');
mongoose.connect(process.env.MONGO_URI);
//To-Do # 2: Create a Model
const personSchema = new mongoose.Schema({
name: { type: String, required: true },
age: Number,
favoriteFoods: [String]
});
const Person = mongoose.model('Person', personSchema);
I still could not find what was the problem as I tried to copy and paste exactly the code given in the solution to the problem suggested by free code camp and even that did not work. I was using replit and perhaps there must be some problem when the free code camp tests interact with the liver server of replit but some expert should answer the problem in detail to save time for other people.
It appears that the problem occurs because a code below is trying to redeclare the "Person" variable (After making it a const). If you look at the boilerplate code on Replit, there were some codes present there already and part of this code has the following:
let Person;
Simply commenting this line out worked for me.

How can i use MongoDB with Cloud Functions for Firebase?

I want to use Cloud Functions for Firebase and MongoDB. The problem is I don't know how to connect my Mongo database with Cloud Functions. My database is deployed at matlab.
I made this schema:
var mongoose = require('mongoose')
var Schema = mongoose.Schema
var patientSchema = new Schema({
name: {
type: String,
required : true,
},
disease:{
type: String,
required : true,
},
medication_provided: {
type: String,
required : true,
},
date : {
type : Date,
}
})
const patient = mongoose.model('patientInfo', patientSchema)
module.exports = patient
Then I require my schema in project index.js file, and export a function called getAllPatient.
const patient = require('../Patient')
const functions = require('firebase-functions');
const mongoose = require('mongoose')
mongoose.connect('mongodb://patient:patient123#ds139869.mlab.com:39869/patient',{useMongoClient: true})
exports.getAllPatient = functions.https.onRequest((request, response) => {
patient.find({}).then((data) => {
response.send(data)
})
})
but gives me an error that "Error: could not handle the request"
I was recently facing this type of error and found that firebase free plan doesn't allow the outbound connections from within the functions. If you need to call external http/tcp connections, you are required to be on the flame or blaze plan. see the screenshot attached below or see the section cloud functions -> outbound networking at this link Firebase Pricing
Try to design the cloud function in a similar way shown in a link below:-
https://github.com/firebase/functions-samples/blob/master/authorized-https-endpoint/functions/index.js
I've tried with mongoose long time back and it was working fine and but it's slow because for every new request it's going to open the mongoose connection and serve you the data.
Hope this helps!!