gpt4 book ai didi

node.js - 无法使用 mongoose 通过 Node 脚本保存 mongodb 记录

转载 作者:太空宇宙 更新时间:2023-11-04 01:15:26 24 4
gpt4 key购买 nike

这是我的 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);
<小时/>

这是一个简单的 Node 脚本,它实例化上面导出的对象并尝试在模型上执行保存命令......

'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(...) 时,它将立即将控制返回到外部执行级别,并且不允许执行保存或保存回调中的任何代码。

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

运行您的示例时,我发现了一些您需要更正的其他拼写错误和错误。检查 SportStanding(s) 模型变量的拼写并确保其在所有位置都匹配。此外,模型上的 find() 需要一个回调,它会返回数据库中的所有记录(作为第二个参数 - 第一个参数是错误标志),因此不需要链式 all() 调用。您想要的保存功能最终应该如下所示:

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

关于node.js - 无法使用 mongoose 通过 Node 脚本保存 mongodb 记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10290542/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com