node.js Mongoose 不会创建新集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31617579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mongoose doesn't create new collection
提问by user3078441
I have following in server.js :
我在 server.js 中有以下内容:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
and a model like this one which works fine ! :
和这样的模型,效果很好!:
var userSchema = new Schema({
firstName: { type: String, trim: true, required: true },
lastName: {type: String, trim: true, required: true},
cellPhoneNumber : {type: Number, unique: true},
email: { type: String, unique: true, lowercase: true, trim: true },
password: String
});
and there's an another model like below one which doesn't work !
还有一个像下面这样的模型不起作用!
var jobSchema = new Schema({
category: {type: Number, required: true},
title: {type: String, required: true},
tags: [String],
longDesc: String,
startedDate: Date,
views: Number,
report: Boolean,
reportCounter: Number,
status: String,
poster: String,
lastModifiedInDate: Date,
verified: Boolean
});
the two var are as follow :
这两个变量如下:
var User = mongoose.model('User', userSchema);
var Job = mongoose.model('Job', jobSchema);
-- mongod doesn't log any error after server.js is connected to it . Does anybody know what's wrong with my second model ?
-- mongod 在 server.js 连接到它后不会记录任何错误。有人知道我的第二个模型有什么问题吗?
回答by matsondawson
The reason is, mongoose only auto-creates collections on startup that have indexes in them. Your User collection has a unique index in it, the Job collection does not. I've just had the same problem today.
原因是,mongoose 只在启动时自动创建包含索引的集合。您的 User 集合中有一个唯一索引,而 Job 集合没有。我今天刚遇到同样的问题。
// example code to test
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
mongoose.model('Test', {
author: {
type: String,
index: true
}
});
回答by JohnnyHK
Mongoose won't create the jobscollection for the model until the first document of that model is saved.
在jobs保存该模型的第一个文档之前,Mongoose 不会为该模型创建集合。
Job.create({category: 1, title: 'Minion"}, function(err, doc) {
// At this point the jobs collection is created.
});
回答by Derese Getachew
First thing to consider is if you have set the autoIndex property on your connection String to True/False;
首先要考虑的是,您是否已将连接 String 上的 autoIndex 属性设置为True/False;
By default autoIndex property is set to True, mongoose will automatically build indexes defined in your schema when it connects. This is great for development, but not ideal for large production deployments, because index builds can cause performance degradation. If this is the case and collections are still not being created in your database the problem might be something else and not related with indexes.
默认情况下 autoIndex 属性设置为 True,猫鼬将在连接时自动构建在您的架构中定义的索引。这对于开发来说非常有用,但对于大型生产部署来说并不理想,因为索引构建会导致性能下降。如果是这种情况,并且您的数据库中仍未创建集合,则问题可能是其他问题,与索引无关。
If you have set autoIndex to false, mongoose will not automatically build indexes for any model associated with this connection i.e. it will not create the collections. In such scenarios you have to manually call model.ensureIndexes(); usually people call this at the same place where they define the models or inside their controllers which in my opinion is bad for production as it does the same thing autoIndex true except this time we are doing it explicitly.
如果您已将autoIndex设置为 false,则mongoose将不会为与此连接关联的任何模型自动构建索引,即它不会创建集合。在这种情况下,您必须手动调用 model.ensureIndexes(); 通常人们在定义模型的同一位置或在他们的控制器内部调用它,在我看来这对生产不利,因为它做同样的事情 autoIndex true 除非这次我们明确地这样做。
What i recommend is creating a separate node.js process to run ensureIndexes on explicitly and separate it from our main application node.js process.
我推荐的是创建一个单独的 node.js 进程来显式运行 ensureIndexes 并将它与我们的主应用程序 node.js 进程分开。
The first advantage of this approach is i can choose to which models i want to run ensureIndexes() and the second one it doesn't run on startup of the application and degrade my application performance rather i run it on demand.
这种方法的第一个优点是我可以选择我想要运行的模型 ensureIndexes() 和第二个它不在应用程序启动时运行并降低我的应用程序性能而是我按需运行它。
Below is sample of the code i use to run ensureIndexes on demand.
下面是我用来按需运行 ensureIndexes 的代码示例。
import mongoose from 'mongoose';
var readline = require('readline');
//importing models i want
import category from '../V1/category/model';
import company from '../V1/company/model';
import country from '../V1/country/model';
import item from '../V1/item/model';
//Connection string options
let options = {useMongoClient:true,
autoIndex:false, autoReconnect:true, promiseLibrary:global.Promise};
//connecting
let dbConnection = mongoose.createConnection('mongodb://localhost:1298/testDB', options);
//connection is open
dbConnection.once('open', function () {
dbConnection.modelNames()
.forEach(name => {
console.log(`model name ${name}`);
dbConnection.model(name).ensureIndexes((err)=> {
if(err) throw new Error(err);
});
dbConnection.model(name).on('index',function(err){
if (err) throw new Error(err);
});
});
console.log("****** Index Creation was Successful *******");
var rl = readline.createInterface({input:process.stdin,output:process.stdout});
rl.question("Press any key to close",function(answer){
process.exit(0);
});
});
回答by Derese Getachew
Another solution for such behavior is adding unique: truein one of Schema objects. It worked for me, mongoose created collection automatically.
这种行为的另一种解决方案是添加unique: true一个 Schema 对象。它对我有用,猫鼬自动创建了集合。
For example:
例如:
const moviesSchema = new Schema({
name: {
type: String,
required: true // I'm writting about such one
}
})

