【发布时间】:2018-01-28 18:14:06
【问题描述】:
我创建了一个 Mongoose 模型并编写了一些代码来测试它是否有效,我尝试保存模型然后显示所有模型,但它没有将任何内容记录到控制台并且模型不是保存。
我的测试代码:
let User = require('./models/user')(MAI);
let myUser = new User({
username: 'Admin',
email: 'admin@example.com',
password: '123456',
});
await myUser.save();
User.find((err, users) => {
if(err) console.log(err);
console.dir(users);
});
我的模特:
const mongoose = require('mongoose');
const UserSchema = mongoose.Schema({
user_id: Number,
username: String,
email: String,
password: String,
verified: { type: Boolean, default: false },
joindate: { type: Date, default: Date.now },
postcount: { type: Number, default: 0 },
});
module.exports = function(MAI) {
UserSchema.plugin(MAI.plugin, {
model: 'User',
field: 'user_id',
startAt: 1,
incrementBy: 1,
unique: true
});
return mongoose.model('User', UserSchema);
}
如果很重要,mongoose 和 mai 初始化:
mongoose.Promise = require('bluebird');
let connection = mongoose.createConnection('mongodb://localhost:27017/forum');
MAI.initialize(connection);
【问题讨论】:
-
您确定没有保存?你检查了
mongocli? -
好吧,如果它没有记录任何东西而不是保存...
-
这是不正确的。您的代码编写为好像
save是同步的。不是。 -
改了我的测试还是不行,是的,运行测试代码的函数是异步的。
-
afaik find 方法将查询对象作为第一个参数而不是 cb,因此您的 cb 它永远不会被调用,因为它被解释为查询对象
标签: node.js mongodb mongoose mongoose-auto-increment