Automattic / mongoose

MongoDB object modeling designed to work in an asynchronous environment.
https://mongoosejs.com
MIT License
26.9k stars 3.83k forks source link

Instance Methods Not Available On Document #9570

Closed HenryDinh86 closed 3 years ago

HenryDinh86 commented 3 years ago

Hi There,

Im new and just got into learning nodejs and mongodb. When i instantiate my model, for some strange reason i dont get the instance methods such as .save(). I have used it in the past and never had a problem until im trying to build my current project.

Any help would be much appreciated. I tried to google search for hours and could not figure this one out.

mongoose connection file:

image

Schema

image

Route

image

Node v14.15.1, Mongoose v5.10.15

AbdelrahmanHafez commented 3 years ago

Welcome @HenryDinh86

Can you add the lines below and share the output?

console.log(Program);
console.log(newProgram);

Also, please avoid sharing screenshots of code, it's easier to share the code itself as text so it's easier for other people trying to help to copy & paste it, it'll be more likely that you'll get the help you need.

HenryDinh86 commented 3 years ago

Welcome @HenryDinh86

Can you add the lines below and share the output?

console.log(Program);
console.log(newProgram);

Also, please avoid sharing screenshots of code, it's easier to share the code itself as text so it's easier for other people trying to help to copy & paste it, it'll be more likely that you'll get the help you need.

Hi @AbdelrahmanHafez ,

Firstly, here are the output from console log: console.log(Program); ---> Model { Program } console.log(newProgram); ---> newProgram : { exercises: [], records: [], _id: 5fb7c1d63334f802e4fbf386, name: 'Test Name', weeks: 8, days: 4, subTitle: 'testing titles', sets: 3, reps: '10', notes: 'testing note', user: 5fb7c01381e72b02c2437767 }

Also sorry about the screenshots. Code as text is below

// mongoose const mongoose = require('mongoose');

mongoose.connect( process.env.MONGODB_URI || 'mongodb://localhost:27017/dbName;', { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false } ); module.exports = mongoose;

//Schema const mongoose = require('mongoose'); const ProgramSchema = new mongoose.Schema( { name: { type: String, minlength: 1, trim: true, required: true }, weeks: Number, days: Number, // eg Day 1 - Upper Body (POWER) subTitle: { type: String, minlength: 1, trim: true }, sets: { type: Number, required: true }, reps: { type: String, trim: true }, notes: { type: String }, user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, exercises: [ { default: [], type: mongoose.Schema.Types.ObjectId, ref: 'Exercise' } ], records: [ { default: [], type: mongoose.Schema.Types.ObjectId, ref: 'Record' } ] }, { timestamps: true } ); const Program = mongoose.model('Program', ProgramSchema); module.exports = Program;

//routes const express = require('express'); const router = express.Router(); const Program = require('../server/models/program');

router.post('/', async (req, res) => { try { const { name, weeks, days, subTitle, sets, reps, notes, user = req.user.id } = req.body;

const newProgram = new Program({
  name,
  weeks,
  days,
  subTitle,
  sets,
  reps,
  notes,
  user
});
newProgram. <----- here when i hit .(dot) i dont get the save()
AbdelrahmanHafez commented 3 years ago

Ok, so seems like Program is a mongoose model, but newProgram is not a document instance. in routes.js can you add the following and share the output?

const mongoose = require('mongoose');

const newProgram = new Program({ name, weeks, ... });
console.log('is a document:',newProgram instanceof mongoose.Document);
console.log('newProgram:', newProgram);
console.log('save:', newProgram.save);

Do you happen to be using any mongoose plugins?

HenryDinh86 commented 3 years ago

Hi @AbdelrahmanHafez

Mongoose plugins you mean using lean() and virtuals? Correct me if im wrong. Im still new to this. If so, i have used them to muck around before and i've removed the code a while ago.

Here is the output from the console logs

is a document: true newProgram: { exercises: [], records: [], _id: 5fba26578eb1d7032f8b1e9e, name: 'Another Test', weeks: 8, days: 4, subTitle: 'Test Title 2', sets: 3, reps: '10', notes: 'Another Test Note', user: 5fb7c01381e72b02c2437767 } save: [Function (anonymous)]

AbdelrahmanHafez commented 3 years ago

According to the logs save is a function, what do you exactly mean when you say that you don't get the methods?

Is there an error that gets thrown? If so, please share it along with the stack trace.

Also, you can read more about mongoose plugins here.

HenryDinh86 commented 3 years ago

Im sorry, what i meant is when i hit (dot) im not seeing intellisense in vscode for the various methods the document has. I use to see them.

Thats why i thought its not working. Some tutorial vids i've seen has intellisense for all its methods

AbdelrahmanHafez commented 3 years ago

Oh, so it's about intellisense.

Can you create an example repository/script that demonstrates the issue? I tried the minimal script below and it's giving me hints for intellisense.

Try installing @mongoose/types and see if it helps npm i --save-dev @types/mongoose.

'use strict';
const mongoose = require('mongoose');
const { Schema } = mongoose;

const userSchema = new Schema({
  name: { type: String }
});

const User = mongoose.model('User', userSchema);

const user = new User();
console.log(user.save);

Screenshot_723

HenryDinh86 commented 3 years ago

I've tried to create another project with this example and its showing this when i hit .save As you can see, i dont know why no intellisense for this model.

image

git repo: git@github.com:HenryDinh86/Test.git

AbdelrahmanHafez commented 3 years ago

I tried with the test repo you provided and things seem to be working for me.

Does intellisense work for anything else, or is it just mongoose? It might be an issue with VSCode, try running vscode in safe mode using the following command in your terminal

code . --disable-extensions

It will open a VSCode window with all extensions disabled, try npm i moment and see if you can get intellisense support for moment or not, we'll also try a simple function in the same file, it's possible that some extension/setting is disallowing the intellisense hints.

const moment = require('moment');

moment().add // should show hints here

/**
 * 
 * @param {Number} x 
 * @param {Number} y 
 * @returns {Number} sum
 */
function add(x,y){
  return x + y;
}

console.log(add); // should show hints

Screenshot_724 Screenshot_725

Also, can you share your VSCode settings.json? CTRL + Shift + P => type in "Open Settings (JSON)", and copy the content here.

HenryDinh86 commented 3 years ago

It seems like its only for mongoose documents. Whenever i instantiate a new mongoose model it happens.

If i call the model itself and hit dot i get the create () image

I'll try to run it in save mode and give you an update

HenryDinh86 commented 3 years ago
const moment = require('moment');

moment().add // should show hints here

/**
 * 
 * @param {Number} x 
 * @param {Number} y 
 * @returns {Number} sum
 */
function add(x,y){
  return x + y;
}

console.log(add); // should show hints

I ran vscode in safe mode and installed moment, everything is okay.

Im also using moment in my project so i created a playground file and mucked around, its giving me intellisense.

I think there's something to do with mongoose...

Here are my Vscode settings: { "workbench.colorTheme": "Material Theme Palenight High Contrast", "workbench.iconTheme": "material-icon-theme", "liveServer.settings.donotShowInfoMsg": true, "workbench.settings.editor": "json", "workbench.settings.useSplitJSON": true, "editor.formatOnSave": true, "prettier.singleQuote": true, "debug.node.autoAttach": "off", "prettier.arrowParens": "always", "workbench.activityBar.visible": true, "workbench.startupEditor": "newUntitledFile", "workbench.statusBar.visible": true, "window.zoomLevel": 0, "javascript.updateImportsOnFileMove.enabled": "never", "editor.fontSize": 16 }

AbdelrahmanHafez commented 3 years ago

Frankly, I am not sure what the issue is here, my last resort would be to manually install @types/mongoose in the repository, if that doesn't help, I suppose we could wait and see if someone else could know what the issue is.

vkarpov15 commented 3 years ago

Realistically, I think the best we can do is to recommend restarting VS code and reinstalling mongoose and @types/mongoose for Mongoose versions before v5.11. Debugging VS Code issues is a deep rabbit hole and we don't have the necessary expertise.