我在尝试实现猫鼬方法时遇到了障碍。 据我所知,我应该能够将带有错误和参数的fn包含在回调中,但是在这种情况下,我会收到此错误:
TypeError:this.Query不是构造函数
型号代码:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
module.exports = mongoose.model('User', new Schema({
name: String,
password: String,
admin: Boolean
}));
破坏代码:
var User = require('./app/models/user');
var { promisify } = require('util');
var findUserPromise = promisify(User.findOne);
...
findUserPromise({ name: req.body.name })
.then(user => console.log("do something with the user"))
.catch(err => { console.log("err ", err) });
非常感谢您的帮助!
答案 0 :(得分:2)
findOne()
的承诺,您只需致电.exec()
:
代替
var findUserPromise = promisify(User.findOne);
...
findUserPromise({ name: req.body.name })
.then(user =>
...
只需使用.exec()
进行调用
:
User.findOne({ name: req.body.name }).exec()
.then(user =>
...
答案 1 :(得分:0)
是的,就像@Jim B回答,猫鼬是诺言友好的。您还可以使用async
和await
const User = require('./app/models/user');
module.export = {
userDetails: async (req, res, next) => {
try {
const user = await User.findOne({ name: req.body.name });
console.log(user);
}
catch(err) {
console.log(err);
}
}
}