Express / Node / Mongoose:为什么在我的router.js中集合上的find()失败?

时间:2019-01-03 22:57:45

标签: express mongoose

当我尝试在Mongo集合上执行“ find”或“ findOne”(使用ExpressJS / Mongoose)时,出现错误: “ TypeError:_Cardsets.Cardset.find(...)。forEach不是函数” (请注意,将集合名称加倍,该名称在数据库中称为“卡片集”(小写和复数)。

来自app.js

import express from 'express';
import path from 'path';
import cookeParser from 'cookie-parser';
import bodyParser from 'body-parser';
import ejs from 'ejs';
import expressValidator from 'express-validator';
import flash from 'connect-flash';
import session from 'express-session';
import passport from 'passport';
const LocalStrategy = require('passport-local').Strategy;
import mongoose from 'mongoose';
import index from './routes/index';
import users from './routes/users';
import mysets from './routes/mysets';
var ensureLoggedIn = require('connect-ensure-login').ensureLoggedIn;

[...]

mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/CRMDB', {
    useMongoClient: true
});
let db = mongoose.connection;

db.on("error", function (error) {
    console.log("fail--->" + error);
});
db.on("open", function () {
    console.log("connected");
});

const app = express();
const PORT = 3000;

[...]

app.use('/mysets/',mysets);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

来自./models/Cardsets.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const CardsetSchema = new Schema({
    _id: String,
    setTitle: String,
    minScore: Number,
    [...]
    dateModified: Date,
    results: Array
});

export const Cardset = mongoose.model('Cardset', CardsetSchema);

来自./routes/mysets.js

import express from 'express';
let router =  express.Router();
import { Cardset } from '../models/Cardsets';

router.get('/', function(req, res){
    var id = req.user._id;
    var dataset = [];
    Cardset.find({creator: id}).forEach(function(myDoc) {
       var tempData = {};
       tempData.setTitle = myDoc.setTitle;
       tempData._id = myDoc._id;
       tempData.language = myDoc.language;
       tempData.dateCreated = myDoc.dateCreated;
       dataset.push(tempData);
       });
       console.log("dataset = "+dataset);
    res.render('pages/mysets', {
       dataset: dataset
    });
});
export default router;

我希望能够将从mongo文档创建的数据对象传递到客户端页面。

1 个答案:

答案 0 :(得分:0)

我认为,您应该在代码中使用 promise ,如下所示:

$data = [
    'grant_type' => 'password',
    'client_id' => $client->id,
    'client_secret' => $client->secret,
    'username' => request('us_username'),
    'password' => request('password'),
    'scope' => '',
];

$reqwest = Request::create('/oauth/token', 'POST', $data);