简体   繁体   English

ZCCADCDEDB567ABAE643E15DCF0974E503Z:usr.findOneAndUpdate 不是 function

[英]Mongoose : usr.findOneAndUpdate is not a function

Error: usr.findOneAndUpdate is not a function错误:usr.findOneAndUpdate 不是 function

Model: 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我想在任务数组中添加一些任务,所以我使用 post 方法,代码是

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....我还阅读了 findOneAndUpdate 的文档,但我没有得到解决方案,请有人可以帮助解决这个错误....
Thank You.谢谢你。

You need to import your model into the file containing your routes.您需要将 model 导入到包含您的路线的文件中。 All mongoose methods are based off the schema that you define, not new instances you create.所有 mongoose 方法都基于您定义的架构,而不是您创建的新实例。

For example, if you have a User model that looks like this:例如,如果您有一个如下所示的用户 model:

// 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您需要导入 model 以便 mongoose 将其识别为一个

Like so (assuming the routes file and user model file are in the same directory):像这样(假设路由文件和用户 model 文件在同一目录中):

const User = require("./user")

router.post("/newTask", (req, res) => {
    User.findOneAndUpdate(//whatever you want to be updated)
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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