Storing and retrieving JavaScript objects in/from MongoDB

后端 未结 2 1458
别跟我提以往
别跟我提以往 2020-12-31 09:36

I am currently playing around with node.js and MongoDB using the node-mongo-native driver.

I tested a bit around using the Mongo console storing and retrieving JS o

相关标签:
2条回答
  • 2020-12-31 10:01

    I just recently realized, that it actually is possible to change an objects prototype in V8/node. While this is not in the standard it is possible in various browsers and especially in V8/node!

    function User(username, email) {
        this.username = username;
        this.email = email;
    }
    
    User.prototype.sendMail = function (subject, text) {
        mailer.send(this.email, subject, text);
    };
    
    var o = {username: 'LoadeFromMongoDB', email: 'nomail@nomail.no'};
    o.__proto__ = User.prototype;
    o.sendMail('Hello, MongoDB User!', 'You where loaded from MongoDB, but inherit from User nevertheless! Congratulations!');
    

    This is used all over various modules and plugins - even core modules make use of this technique, allthough it is not ECMAScript standard. So I guess it is safe to use within node.js.

    0 讨论(0)
  • 2020-12-31 10:20

    I'm not sure I'm following you question exactly... but fwiw one thing came to mind: Have you checked out the Mongoose ORM? (http://mongoosejs.com/)

    It gives you a lot of options when it comes to defining models and methods. In particular "Virtuals" might be of interest (http://mongoosejs.com/docs/virtuals.html).

    Anyway, hope it helps some!

    0 讨论(0)
提交回复
热议问题