gpt4 book ai didi

javascript - Mongoose 随机不起作用?

转载 作者:行者123 更新时间:2023-11-28 20:01:26 24 4
gpt4 key购买 nike

我正在使用 mongoose-random 包从我的 MongoDB 数据库中获取随机项目。这是我的代码:

// Bring Mongoose into the app
var mongoose = require( 'mongoose' );
var random = require('mongoose-random');

var DBNAME = 'test';
var COLLNAME = 'koleksigj';
var DBURI = 'mongodb://localhost/' + DBNAME;

// Connect to DB
mongoose.connect(DBURI);

// Create the schema
var quizSchema = new mongoose.Schema({ title: String, body: String });
quizSchema.plugin(random);

// Make the model
var Quiz = mongoose.model('Quiz', quizSchema);

// Make query
Quiz.findRandom(function (err, quiz) {
console.log(quiz);
})

// CONNECTION EVENTS
// When successfully connected
mongoose.connection.on('connected', function () {
console.log('Mongoose default connection open to ' + dbURI);
});

// If the connection throws an error
mongoose.connection.on('error',function (err) {
console.log('Mongoose default connection error: ' + err);
});

// When the connection is disconnected
mongoose.connection.on('disconnected', function () {
console.log('Mongoose default connection disconnected');
});

// If the Node process ends, close the Mongoose connection
process.on('SIGINT', function() {
mongoose.connection.close(function () {
console.log('Mongoose default connection disconnected through app termination');
process.exit(0);
});
});

看来我的 mongoose-random 用法与文档 here 类似。

但是我收到此错误消息:

hfz:mong-final Hfz$ node all.js

/Users/Hfz/Dev/nodejs/mong-euro/mong-final/all.js:23
Quiz.findRandom(function (err, quiz) {
^
TypeError: Object function model(doc, fields, skipId) {
if (!(this instanceof model))
return new model(doc, fields, skipId);
Model.call(this, doc, fields, skipId);
} has no method 'findRandom'
at Object.<anonymous> (/Users/Hfz/Dev/nodejs/mong-euro/mong-final/all.js:23:6)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3

最佳答案

如果您查看 Git repository 中的示例它与 NPM 上的稍有不同。

将添加插件到 quizSchema 的行更改为调用 random(),而不是仅仅将其传入:

quizSchema.plugin(random());

关于javascript - Mongoose 随机不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21603254/

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