Mongoose : usr.findOneAndUpdate is not a function - javascript

Error : usr.findOneAndUpdate is not a function
Model:
var mongoose = require('mongoose')
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt')
var schema = new Schema({
email: { type: String, require: true },
username: { type: String, require: true },
password: { type: String, require: true },
creation_dt: { type: String, require: true },
tasks:[{type:{type:String}}]
});
module.exports = mongoose.model('User',schema)
i want to Add some Task in tasks array so i use post method for That and code is
Code:
router.post('/newTask', function (req, res, next) {
var dataa = {
pName: req.body.pName,
pTitle: req.body.pTitle,
pStartTime: req.body.pStartTime,
pEndTime: req.body.pEndTime,
pSessionTime: req.body.pSessionTime
}
var usr = new User(req.user)
usr.findOneAndUpdate(
{_id:req.user._id},
{$push:{tasks:dataa}}
)
try {
doc = usr.save();
return res.status(201).json(doc);
}
catch (err) {
return res.status(501).json(err);
}
})
i also read the documentation of findOneAndUpdate but i din't get solution please someone can Help out of this error....
Thank You.

You need to import your model into the file containing your routes. All mongoose methods are based off the schema that you define, not new instances you create.
For example, if you have a User model that looks like this:
// file is named user.js
const mongoose = require('mongoose')
const userSchema = new mongoose.Schema ({
username: String,
password: String
})
module.exports = mongoose.model("User", userSchema)
You need to import the model so mongoose recognizes it as one
Like so (assuming the routes file and user model file are in the same directory):
const User = require("./user")
router.post("/newTask", (req, res) => {
User.findOneAndUpdate(//whatever you want to be updated)
})

Related

Express/mongoose returns empty array when trying to get request

I am trying to get the list of books from the database. I inserted the data on mongoose compass. I only get an empty array back.
//Model File
import mongoose from "mongoose";
const bookSchema = mongoose.Schema({
title: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
releasedDate: {
type: String,
required: true,
},
});
const Book = mongoose.model("Book", bookSchema);
export default Book;
//Routes file
import express from "express";
import Book from "./bookModel.js";
const router = express.Router();
router.get("/", async (req, res) => {
const books = await Book.find({});
res.status(200).json(books);
});
make sure you have books data in db.if it is there then try to add then and catch blocks to your code. Then you will get to know what is the error.
await Book.find({})
.then((data) =>{
res.send(data)
})
.catch((err) =>{
res.send(err)
})
When you create your model, change mongoose.model by new Schema and declare _id attribute like:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
const Book = new Schema({
_id: { type: Schema.ObjectId, auto: true },
// other attributes
})
Update: If it doesn't seem to work, try changing _id with other names such as bookID or id, that can be the error, read https://github.com/Automattic/mongoose/issues/1285

is this code true to query all documents in mongodb via mongoose?

i'm using MongooseJS and doesn't return anything in console or res.json
is it about find function ?
const router = require("express").Router();
var Panel = require("../models/Panel");
router.get("/panels", (req, res) => {
Panel.find({}, function(err, panels) {
if (err) res.send(err);
console.log(panels);
res.json(panels);
});
});
This is the mongoose model for Panel section
const mongoose = require("mongoose");
const Panel = mongoose.model(
"Panel",
new mongoose.Schema({
name: String,
const: Number,
salons: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Salon"
}
]
})
);
module.exports = Panel;
Problem solved, by catching errors, and trying to use anyone can access database, it was about my proxy :)

NodeJs-TypeError: Category.find is not a function

i am working on NodeJs application its blog application. i am trying to fetch
Category data, fetching process i am getting this error
TypeError: Category.find is not a function
at getCategories (D:\OnlyNodeJs\CMS App\controllers\adminController.js:54:18)
here is file..
adminController.js
const Category = require('../models/CategoryModel');
getCategories: (req, res) => {
Category.find()
.then(cats => {
res.render('admin/category/index', { categories: cats});
});
},
adminRoutes.js
router.route('/category')
.get(adminController.getCategories);
CategoryModels.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CategorySchema = new Schema({
title: {
type: String,
required: true
}
});
module.exports = {Category: mongoose.model('category', CategorySchema )};
any help is highly appreciated.
You export an object with a Category prop, but then you import it as though the Category is the only thing being exported. Either update the import to :
const { Category } = require('../models/CategoryModel');
Or update the export to:
module.exports = mongoose.model('category', CategorySchema);

Trying to populate my user model and getting a Type Error

In my program I want to populate my index page with a model called a group. Previously I just showed all the groups that existed in the database, but now I want to only show the groups that the user who is logged in is associated with.
Here are the models:
Group Model
var mongoose = require("mongoose");
var groupSchema = new mongoose.Schema({
name: String,
thumbnail: String,
description: String,
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
},
inviteCode: String,
images: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Image"
}
],
users: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}
] });
module.exports = mongoose.model("Group", groupSchema);
User Model
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var UserSchema = new mongoose.Schema({
username: String,
password: String,
groups:
[
{
type: mongoose.Schema.Types.ObjectId, //referencing model by id
ref: "Group" //name of the model
}
],
images:
[
{
type: mongoose.Schema.Types.ObjectId, //referencing model by id
ref: "Image" //name of the model
}
]
});
UserSchema.plugin(passportLocalMongoose); //add in local mongoose methods to user
module.exports = mongoose.model("User", UserSchema);
My Index Route:
//Index Route
router.get("/", middleware.isLoggedIn, function(req, res){
var user = req.user;
user.populate("groups").exec(function(err, allGroups){
if(err){
console.log(err);
} else {
res.render("groups/show", {groups: allGroups});
console.log(allGroups);
}
});
});
And this is the error I get:
TypeError: user.populate(...).exec is not a function
I am not sure why I cant use the populate method with my user model, can someone explain me an alternative to achieve the desired outcome. Thank you.
I think the problem is that req.user is not a schema, so .populate is not a method carried by that variable in its object prototype. Hence the terminal telling you it's not a function.
You have to require the User schema like this in your index route:
const User = require("./models/user");
Then find the user by its id then populate it:
//Index Route
router.get("/", middleware.isLoggedIn, function(req, res){
var user = req.user;
User.findById(req.user._id, function(err, foundUser) {
let user = foundUser;
user.populate("groups").exec(function(err, allGroups){
if(err){
console.log(err);
} else {
res.render("groups/show", {groups: allGroups});
console.log(allGroups);
}
});
});
});
Let me know if it works!

passport User is not a function

I keep getting the same error "User is not a function" when I call my API method.
Has anybody got an ideas why this might be.
Api method:
//need to export the api methods.
var User = require('../models/user');
var passport = require('passport');
module.exports.create = function(req, res) {
//TODO: error checking.
var user = new User();
console.log(req);
user.firstName = req.body.firstName;
user.secondName = req.body.secondName;
user.email = req.body.email;
user.setPassword(req.body.password);
user.save(function(err) {
res.status(200);
});
};
user model:
var mongoose = require('mongoose');
var crypto = require('crypto');
var userSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true
},
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
hash: String,
salt: String
});
userSchema.methods.setPassword = function(password){
};
userSchema.methods.validPassword = function(password) {
};
mongoose.model('User', userSchema);
Let me know if I need to enter any more files.
Thanks
You need to export the mongoose model you created at the end of the User Model file. Something like
module.exports = mongoose.model('User', userSchema);

Categories

Resources