我想创建一个数据库,其中包含在我的data.js文件中创建的模式,但数据库没有创建
index.js:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var path = require('path');
var expressValidator = require('express-validator');
var mongoose = require('mongoose');
var Data = require('./models/data');
mongoose.connect('mongodb://localhost:27017/data');
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'mongodb connection
error'));
db.once('open', () => console.log('mongodb connected'));
//app.use(expressValidator(customValidators));
app.use(express.static(path.join(__dirname,'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/',function(req,res){
var d = new Data({optionName:"switchOnLights",optionValues:
["switchOnLights"]});
d.save(err =>{console.error(err)});
res.render('index');
});
app.post('/users/add',function(req,res){
var text = req.body.text;
var option = req.body.option;
db.Data.update(
{optionName:option},
{$addToSet:{optionValues:text}})
});
app.listen(3001,function(){
console.log("server is running");
})
data.js(我的模特):
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
var dataSchema = new Schema({
optionName:String,
optionValues:[{type:String}]
});
var Data = mongoose.model('Data',dataSchema);
module.exports = Data;
我还尝试通过在访问主页时添加新文档来测试数据库,但它仍然没有创建数据库
答案 0 :(得分:1)
首先应创建模型实例,然后将其保存到数据库中。 而不是
db.Data.update()
尝试以下代码块:
var d = new Data({//columns});
d.save(err => {//handle errors});
有关详细信息,请查看mongoos official docs