我是Node.js的新手,这是我第一次使用MongoDB。
连接似乎有效,但从未创建数据库。
我创建了用户模型,因为我认为需要创建一条记录才能创建数据库
我不确定我在这里想念什么。
index.js
import mongoose from 'mongoose';
//DB setup
mongoose.connect("mongodb://localhost:27017/hotel", {
useNewUrlParser: true
});
// CONNECTION EVENTS
// When successfully connected
mongoose.connection.on('connected', function() {
console.log('Mongoose default connection open to ' + 'mongodb://localhost:27017/hotel');
});
// 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);
});
});
user.js
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
//Defined models
const userSchema = new Schema({
email: { type: String, unique: true, lowercase: true },
password: String
});
//Create model class
const ModelClass = mongoose.model('user', userSchema);
//Export the model
module.exports = ModelClass;
我也尝试添加.save()函数,但似乎没有用
ModelClass.save(function (err) {
if (err) return handleError(err);
// saved!
});
答案 0 :(得分:0)
尝试使用原始值初始化猫鼬模型,然后将其保存。即
const ModelClass = mongoose.model('user', userSchema);
var user = new ModelClass({ email: 'Rover@rover.in', password: 'dog' });
// Now user.save function