简体   繁体   English

model.find 不是 function

[英]model.find is not a function

I am trying to learn node.js with mongoose.我正在尝试用 mongoose 学习 node.js。 Simply want to read from database and display result in a browser.只想从数据库中读取并在浏览器中显示结果。 I have index.js where I compiled model from schema as我有 index.js,我从架构编译 model 为

var mlink = mongoose.model('mlink',mlinkSchema)

Then I exported it so as to use it in server.js file as然后我导出它以便在 server.js 文件中使用它

module.exports = mongoose.model('mlink',mlinkschema);

Under server.js, I require it as在 server.js 下,我要求它为

const mlink = require(__dirname, "../Scripts/index.js");

And now, I am using express router as below现在,我正在使用如下的快速路由器

const express = require('express');
const app = express();
const router = express.Router();
app.use("/", router);
router.route("/Scripts").get(function(req,res){
  mlink.find({},function(err, result){
    if (err) {
      res.send(err);
    }
    else {
      res.send(result);
    }
  });
});

Here I keep on getting error as mlink.find is not a function.在这里我不断收到错误,因为 mlink.find 不是 function。 Please help I am stuck.请帮助我卡住了。

Instead of this而不是这个

module.exports = mongoose.model('mlink',mlinkschema);

It should be它应该是

module.exports = mlink;

If you have a correct model than如果你有一个正确的 model 比

module.exports = mongoose.model('mlink',mlinkSchema);

should work (you had a typo in mlinkSchema it needs to have a capital S)应该可以工作(您在mlinkSchema中有错字,它需要有一个大写的 S)

You would import a model like this:您将像这样导入 model:

const mlink = mongoose.model("mlink");

Getting data from MongoDB is time consuming it should be an asynchronous function从 MongoDB 获取数据很耗时,应该是异步的 function

router.route("/Scripts").get(async function(req,res){
  await mlink.find({},function(err, result){
    if (err) {
      res.send(err);
    }
    else {
      res.send(result);
    }
  });

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

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