gpt4 book ai didi

node.js - 如何在 Node.js 中正确使用 Mongoose 模型?

转载 作者:太空宇宙 更新时间:2023-11-04 00:54:23 25 4
gpt4 key购买 nike

我正在尝试使用 Mongoose 来控制我的数据库逻辑和事务。我已经获得了架构定义,并且正在导出模型。

但是,当我尝试使用模型时,它会失败并显示如下消息:

return mongoose.model('Report', reportSchema);
} has no method 'find'
...

这是我的模型导出:

module.exports = (function() {

var mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;

var reportSchema = mongoose.Schema({

category: ObjectId,
authorName: String,
authorEmail: String,
text: String,
address: String,
coordinates: {
type: "Point",
coordinates: [Number,Number]
},
date: {
type: Date,
default: new Date()
},

comments: Array
});

return mongoose.model('Report', reportSchema);
});

这就是我的 Controller 函数如何使用 mongoose 进行编码:

module.exports = (function() {

var mongoose = require('mongoose');
var Report = require('../models/Report');
var Category = require('../models/Category');

function _getReports (request,response,next) {

var take = request.query.take;
var skip = request.query.skip;

Report.find({}).limit(take).skip(skip).exec(function (err,reports) {

callback(err,reports,response);
});
}

function _getReport (request,response,next) {

var id = request.params.id;

Report.findById({_id: id}, function (err,report) {

callback(err,report);
});
}

function _createReport (request,response) {

var newReport = new Report();

newReport.text = request.body.text;
newReport.category = request.body.category;
newReport.author = request.session.userId;

newReport.save(function (err,savedReport) {
callback(err,savedReport._id,response);
});

}

function _updateReport (request,response) {

var id = request.params.id;
var update = request.body.report;

Report.findByIdAndUpdate(id, update, function (err,foundReport) {

callback(err,foundReport,response);
});
}

function _deleteReport (request,response) {

var id = request.params.id;

Report.findByIdAndRemove(id, function (err,foundReport) {
callback(err,foundReport,response);
});
}

function _getReports (request,response,next) {

var take = request.query.take;
var skip = request.query.skip;

Report.find({}).limit(take).skip(skip).exec(function (err,reports){

callback(err,reports,response);
});
}

function _getCategories (request,response) {

var take = request.query.take;
var skip = request.query.skip;

Report.find({}).limit(take).skip(skip).exec(function (err,reports) {

callback(err,reports,response);
});
}

function _getCategoryReports (argument) {

var _id = mongoose.Types.ObjectId(request.params.id);

Report.find({category:id},{category:false},function (err, foundReports) {
callback(err,foundReports,response);
});
}

function _createCategory (request,response) {

var newCategory = new Category();

newCategory.name = request.body.name;

newCategory.save(function (err,savedCategory) {
callback(err,savedCategory._id,response);
});
}

function _updateCategory (request,response) {

var id = request.params.id;
var update = request.body.category;

Category.findByIdAndUpdate(id, update, function (err,foundCategory) {

callback(err,foundCategory,response);
});
}

function _deleteCategory (request,response) {

var id = request.params.id;

Category.findByIdAndRemove(id, function (err,foundCategory) {
callback(err,foundCategory,response);
});
}



function callback (err,object,response) {

if (err)
response.status(500).send(JSON.stringify(err));

response.send(JSON.stringify(object));
}


var apiController = {
getReports: _getReports,
getReport: _getReport,
createReport: _createReport,
updateReport: _updateReport,
deleteReport: _deleteReport,
getCategories: _getCategories,
getCategoryReports: _getCategoryReports,
createCategory: _createCategory,
updateCategory: _updateCategory
}

return apiController;
})();

在此之前,确保 Mongoose 连接:

var connectToMongoose = function (mongoose,app) {

var connect = function () {
var options = { server: { socketOptions: { keepAlive: 1 } } };
mongoose.connect( 'mongodb://localhost/data4', options);
}


mongoose.connection.on('connected', function () {

console.log('Connected to db');

app.listen(32884, function() {
console.log("Listening at \"data4 port\" @:32884");
});
})

mongoose.connection.on('error', function (err) {
console.log(err);
});

mongoose.connection.on('disconnected', function () {
console.log('Disconnected from db, attempting to connect again...');
app.close();
connect();
});

connect();
};

module.exports = connectToMongoose;

require('./db/mongoose-connect.js')(mongoose,app); 调用

我做错了什么?

最佳答案

我立即发现了几个问题。

首先,我没有看到 mongoose.connect() 行将您的 mongoose ODM 显式连接到 mongo 服务器+数据库。一个例子是:

var mongoose = require( 'mongoose' ),
Schema = mongo.Schema,
ObjectId = mongo.Schema.ObjectId;

mongoose.connect( 'mongodb://localhost/db_name' );

您的架构导出看起来不错。但是您使用匿名函数作为导出。既然您这样做了,您的 require 语句需要稍微改变一下:

var Report = require('../models/Report')();
var Category = require('../models/Category')();

注意 require 语句末尾的 ()。您需要执行定义为模型文件的 module.export 的函数。

编辑:我看到您添加了 Mongoose 连接代码。此时,执行您在模型文件中分配的 module.exports 函数应该允许您的 mongoose 模型按预期运行。

关于node.js - 如何在 Node.js 中正确使用 Mongoose 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30675729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com