我遇到Mangoose和NodeJS的问题。我解释一下:
但是它不起作用,我没有错误,但文档没有创建。
这是我的代码:
Server.js:
// Set up
var express = require('express');
var app = express();
var mongoose = require('mongoose');
//Connection
var connection = mongoose.createConnection('mongodb://localhost/babyfootdb');
connection.on("error", function(){
console.log("Error");
});
connection.on("open", function(){
console.log("Connected");
});
// Models
require("./models")(app);
在models.js中:
var mongoose = require('mongoose');
module.exports = function(app){
//Schema
var playerSchema = mongoose.Schema({
name: String,
mail : String,
password: String,
}, {collection : 'players'});
//Model
var Player = mongoose.model('Player', playerSchema);
//Create
Player.create({name : "test",mail : "test",password : "test"},
function(){
Player.find(function(err, players){
console.log("find");
if(err) return console.error(err);
console.log(players);
});
});
}
抱歉我的英语不好但是如果你有任何想法可以帮我提前谢谢。
答案 0 :(得分:1)
它已经修好了。我换了:
//Connection
var connection = mongoose.createConnection('mongodb://localhost/babyfootdb');
connection.on("error", function(){
console.log("Error");
});
connection.on("open", function(){
console.log("Connected");
});
通过:
mongoose.connect('mongodb://localhost/bfdb');
mongoose.connection.on("error", function(){
console.log("Error");
});
mongoose.connection.on("open", function(){
console.log("Connected");
});
答案 1 :(得分:0)
由于您将模型声明为Player
,请尝试使用Player.create(documentToBeCreated)
。您还没有在架构中定义pseudo
字段,但是您尝试在create()
中使用它,因此可能会导致一些问题。创建文档的另一种方法是:
new Player(docToBeCreated).save(callback(err, player))
。如果这有帮助,请告诉我们:)