无法使用mongoose通过节点脚本保存mongodblogging

这是我的js文件描述模式和API的不起作用。 当我通过命令行工具来做到这一点的时候,模式非常简单,我已经实现了一些简单的查找命令。

'use strict' var util = require('util'); var bcrypt = require('bcrypt'); var mongoose = require('mongoose'); var Schema = mongoose.Schema; var validatePresenceOf = function(value){ return value && value.length; }; var toLower = function(string){ return string.toLowerCase(); }; var SportsStandings = new Schema({ 'sport' : { type : String, validate : [validatePresenceOf, 'a sport is required'], set : toLower }, 'league' : { type : String, validate : [validatePresenceOf, 'a league is required'], set : toLower }, 'division' : { type : String, validate : [validatePresenceOf, 'a division is required'], set : toLower }, 'teamName' : { type : String, validate : [validatePresenceOf, 'a teamName is required'], set : toLower }, 'wins' : { type : Number, min: 0, validate : [validatePresenceOf, 'wins is required'], }, 'losses' : { type : Number, min: 0, validate : [validatePresenceOf, 'losses is required'], } }); SportsStandings.statics.findTeamRecord = function(sport, league, division, teamName, cb) { return this.find({'sport' : sport, 'league' : league, 'division' : division, 'teamName': teamName}, cb); }; SportsStandings.statics.findBySport = function(sport, cb) { return this.find({'sport' : sport}, cb); }; module.exports = mongoose.model('SportsStanding' , SportsStandings); 

这里是简单的节点脚本,实例化上面导出的对象,并尝试在模型上执行保存命令…..

 'use strict' var util = require('util'); var mongoose = require('mongoose'); var db = mongoose.connect('mongodb://localhost/mydb'); var SportsStanding = require('../schemas/SportsStandings'); var record = new SportsStanding({ 'sport' : 'mlb', 'league' : 'AL', 'divison' : 'east', 'teamName' : 'New York Yankees', 'wins' : 10, 'losses' : 1}); record.save(function(err) { console.log('error: ' + err); SportsStandings.find().all(function(arr) { console.log(arr); console.log('length='+arr.length); }); }); process.exit(); 

请记住,使用node.js进行编程时,必须非常小心使用事件驱动的编程风格。 您的代码的问题似乎是您在外部执行级别调用process.exit() 。 当你调用record.save(...)它会立即将控制权返回给外部执行层,不允许执行保存或保存callback中的任何代码。

为了解决这个问题,你需要将你的process.exit()移动到最内部的callback函数的末尾,然后你应该看到你期望的结果。

运行你的例子,我发现了一些你需要纠正的其他错别字和错误。 检查您的SportStanding(s)模型variables的拼写,并确保它匹配到处。 此外,你的模型上的find()需要一个callback,它返回数据库中的所有logging(作为第二个参数 – 错误标志是第一个),所以不需要链接的all()调用。 你想要的保存function最终应该是这样的:

 record.save(function(err) { console.log('error: ' + err); SportsStandings.find(function(err, arr) { console.log(arr); console.log('length='+arr.length); process.exit(); }); });