简体   繁体   中英

Mongoose : usr.findOneAndUpdate is not a function

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)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM