【问题标题】:Sails.js - how to update nested modelSails.js - 如何更新嵌套模型
【发布时间】:2013-11-05 00:39:04
【问题描述】:
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'
}

我目前注册用户,然后在注册后更新个人资料信息。如何将配置文件数据添加到此模型?

我在其他地方读到 push 方法应该可以工作,但它没有。我收到此错误: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)
            });

        });

【问题讨论】:

  • 您使用的是哪个数据库?

标签: javascript node.js sails.js


【解决方案1】:

@Zolmeister 是正确的。 Sails 仅支持以下模型属性类型

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

它们也不支持关联(否则在这种情况下很有用)

GitHub Issue #124.

您可以绕过帆并使用诸如此类的 mongo 的本机方法来解决此问题:

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

    });

});

请记住,他们的垫片存在是有原因的。绕过它们将删除一些在后台处理的功能(将 id 查询转换为 ObjectId,通过套接字发送 pubsub 消息等)

【讨论】:

  • 不相信这是可行的 - collection.find 没有承诺风格的 done 方法。
  • 它可能在 v0.10 中发生了变化。如果是这种情况,它可能仍然遵循将回调作为最后一个参数传递给 .find() 的标准
【解决方案2】:

目前 Sails 不支持嵌套模型定义(据我所知)。您可以尝试使用 'json' 类型。 之后,您只需:

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

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

【讨论】:

  • 令人失望的是 Sails 是为 mongoDB 构建的......这就是使用面向文档的 DB 的优势。
【解决方案3】:

来不及回复,但对于其他人(作为参考),他们可以这样做:

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) {
  });           
});

【讨论】:

    猜你喜欢
    • 2014-07-24
    • 2013-09-18
    • 1970-01-01
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    • 2015-06-03
    • 2019-03-15
    • 1970-01-01
    相关资源
    最近更新 更多