简体   繁体   English

在mongodb中的模式中定义的属性未在节点中显示hisOwnProperty

[英]The property defined in schema in mongodb is not showing hisOwnProperty in nodes

My user schema is 我的用户架构是

    var mongoose    =   require('mongoose');
    var userSchema  = mongoose.Schema({
          firstName     : String,
          lastName      : String,
          ...
    })

    module.exports = mongoose.model('user', userSchema,'user');

My find query on user DB 我在用户数据库上查找查询

User.findById(userId,function(error,user){
    if(!error){
       console.log(user) //correctly print user schema as described above with _id
       for (var key in user) {
          if (user.hasOwnProperty(key)) {
            console.log("key ", key); //not print firstName, lastName
          }
       }
    }
})

The for in loop doesn't work as excepted, it prints different properties which is not in schema for in循环不起作用,它打印不在模式中的不同属性

That's because the returned user is a mongoose model . 那是因为返回的usermongoose model It has some other properties build it in it's prototype. 它有一些其他属性在它的原型中构建它。

If you want to iterate over the user properties, you need to do this: 如果要迭代用户属性,则需要执行以下操作:

   console.log(user)
   var objUser = user.toObject();
   for (var key in objUser) {
      if (objUser.hasOwnProperty(key)) {
        console.log("key ", key);
      }
   }

The toObject() function will turn your mongoose model into a pure Javascript object. toObject()函数会将您的toObject()模型转换为纯Javascript对象。 But, if you do this, you need to remember that mongoose model functions won't work on the pure object (because it is not a mongoose model anymore). 但是,如果你这样做,你需要记住,猫鼬模型函数不适用于纯对象(因为它不再是猫鼬模型)。 So if you still need to use them, you need to keep a reference to the original user model. 因此,如果您仍然需要使用它们,则需要保留对原始用户模型的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM