Sails.js - how to update nested model

落爺英雄遲暮 提交于 2020-01-02 06:48:32

问题


attributes: {
    username: {
        type: 'email', // validated by the ORM
        required: true
    },
    password: {
        type: 'string',
        required: true
    },
    profile: {
        firstname: 'string',
        lastname: 'string',
        photo: 'string',
        birthdate: 'date',
        zipcode: 'integer'
    },
    followers: 'array',
    followees: 'array',
    blocked: 'array'
}

I currently register the user then update profile information post-registration. How to I go about adding the profile data to this model?

I read elsewhere that the push method should work, but it doesn't. I get this error: TypeError: Object [object Object] has no method 'push'

        Users.findOne(req.session.user.id).done(function(error, user) {

            user.profile.push({
                firstname : first,
                lastname : last,
                zipcode: zip
            })

            user.save(function(error) {
                console.log(error)
            });

        });

回答1:


@Zolmeister is correct. Sails only supports the following model attribute types

string, text, integer, float, date, time, datetime, boolean, binary, array, json

They also do not support associations (which would otherwise be useful in this case)

GitHub Issue #124.

You can get around this by bypassing sails and using mongo's native methods like such:

Model.native(function(err, collection){

    // Handle Errors

    collection.find({'query': 'here'}).done(function(error, docs) {

        // Handle Errors

        // Do mongo-y things to your docs here

    });

});

Keep in mind that their shims are there for a reason. Bypassing them will remove some of the functionality that is otherwise handled behind the scenes (translating id queries to ObjectIds, sending pubsub messages via socket, etc.)




回答2:


Currently Sails doesn't support nested model definitions (as far as I know). You could try using the 'json' type. After that you would simply have:

user.profile = {
  firstname : first,
  lastname : last,
  zipcode: zip
})

user.save(function(error) {
  console.log(error)
});



回答3:


Too late to reply, but for others (as a reference), they can do something like this:

Users.findOne(req.session.user.id).done(function(error, user) {
  profile = {
            firstname : first,
            lastname : last,
            zipcode: zip
      };
  User.update({ id: req.session.user.id }, { profile: profile},         
        function(err, resUser) {
  });           
});


来源:https://stackoverflow.com/questions/19780009/sails-js-how-to-update-nested-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!