Console.log打印[Object SequelizeInstance:User]

时间:2018-08-27 23:24:31

标签: node.js sequelize.js

所以,我对续集有点陌生。以前(我不知道可能是旧版本还是其他代码),console.log会打印整个对象及其所有元数据属性,但到目前为止,它会打印[object SequelizeInstance:users]

我尝试使用raw:true属性(以避开元数据地狱),该属性返回[object Object],然后用util.inspect包装它以打印它。

代码:

User.findOne({
        attributes : [
            [sequelize.fn('max', sequelize.col('id')), 'id']
        ],
        raw: true //if enabled
    })
    .then(function(user){
    //returns [object SequelizeInstance:users] or if raw:true then [object Object]
        console.log("User object is "+user);
    //both are printed easily with this
        console.log(util.inspect(user,false,null));
    //OR
        console.log(JSON.stringify(user, null, 4))
    })

这是登录用户对象的唯一方法,还是因为以前我可以console.log(user)来获取所有数据(元数据地狱)而丢失了某些东西吗?

2 个答案:

答案 0 :(得分:2)

首个黑白(原始:true)和(原始:false或无)

// When raw : true --> Will return plain json object nothing added from sequlize 
console.log("User object is "+user);

// When raw : false --> Will return sequlize object , so that you can perform verious opreation upon them
console.log("User object is "+user);
user.update({ name : 'New Name' }) // <-- Like this , you dont need to define where , coz its already object that is returned by sequlize

原因为何您要获取[Object Object]和[object SequelizeInstance:users]是:

console.log("User object is "+user); // Will show [Object Object] cos you are appending object with string
console.log("User object is " , user); // This will print out whole object clearly  

答案 1 :(得分:1)

  

以前[...] console.log会打印整个对象

我怀疑您使用了这个确切的说法:

  

console.log("User object is "+user);

在这里,JS要做的第一件事是考虑"User object is "+user,因此由于user运算符,它将+转换为字符串,然后 传递将 string 连接到console.log

如果您尝试console.log(user);,则应该具有预期的输出。您可能还会提供几个参数,以便每个参数都按“原样”记录,这有助于跟踪显示的内容而不会干扰记录的数据:console.log("User object is", user);