假设我在文件的开头有这个定义:
const ObjectId = mongoose.Types.ObjectId;
Run Code Online (Sandbox Code Playgroud)
您应该更喜欢哪一个?为什么?
// 1
new ObjectId;
// 2
new ObjectId();
// 3
ObjectId();
Run Code Online (Sandbox Code Playgroud)
官方文档建议使用new ObjectId
. 对我来说,new ObjectId()
感觉更自然,但它们每个都会生成一个新的 ObjectId,并且我在 SO 的问题和答案中看到了它们每个的示例。
更新:
让我澄清一下:我知道为什么以及如何在 JavaScript 中使用 new 运算符,我只是想找出new
用于生成 ObjectID 时是否有任何显着差异。(该函数的行为不同,引发错误等......)
我正在尝试将旧的 mongoose Promise 代码转换为 Native ES6 Promise。我收到了 catch 中抛出的所有错误,我可以将其记录在控制台中,但是当我尝试将其传递给响应对象时,我得到空对象。以下是我的代码
module.exports.login = function(req, res) {
var userPromise = User.findOne({email:req.body.email}).exec();
userPromise.then(function(user) {
if(!user){
throw new Error("step 1 failed!");
}
})
.then(function(user) {
if(!user.comparePassword(req.body.password)){
throw new Error("step 2 failed!");
}else {
return res.json({token: jwt.sign({email:user.email, name:user.name, _id: user._id}, 'SOMETOKEN')});
}
})
.catch(function(err) {
console.log('Error: '+err);
return res.status(401).send(err);
});
};
Run Code Online (Sandbox Code Playgroud)
请让我知道我是否走在正确的道路上或者我在这里犯了一些错误。提前致谢。