【问题标题】:Pushing object into mongoDB, ["object Object"] is saved将对象推入 mongoDB,["object Object"] 被保存
【发布时间】:2015-02-18 10:36:16
【问题描述】:

对不起,如果这是一个重复的问题,我真的无法用这里提供的任何信息来解决它。

基本上我的 User.js mongoDB 架构中有这个:

notifications: [{
        type: String,
        story: String,
        seen: Boolean,
        createdTime: Date,
        from: {
            name: String,
            username: String,
            id: mongoose.Schema.ObjectId
        }
    }]

在我查询用户之后,这是我推送这个对象的操作:

var notifObj = {

    type: notification.type,
    story: notification.story || ' ',
    seen: false,
    createdTime: new Date(),
    from: {
        name: notification.from.firstName + " " + notification.from.lastName,
        username: notification.from.username,
        id: notification.from._id
    }
};

进入 mongoDB 数据库:

user.notifications.push(notifObj);

User.update({
    _id: notification.to
}, user, function(err, data) {

    if (err) {

        deferred.reject({
            err: err
        });
    }

    //Tell sender everything went alrgiht
    deferred.resolve(data);
});

【问题讨论】:

  • 你确定它保存为 [object object],还是当你尝试 console.log 对象时它就是这样显示的?尝试在简单类型的对象上记录属性,例如 notifObj.seen
  • 检查答案,你将不确定是笑还是捂脸...:/

标签: javascript node.js mongodb object


【解决方案1】:

我发现为什么 mongoDB 总是将我的 Object 转换为 String 并给我一个 ["object Object"] ,原因很简单 - 永远不要使用保留/常用词作为对象键。 MongoDB 将我的 notification: {type: String, ...} 解释为一个字段,该字段将字符串作为值而不是作为通知,它具有类型、已见和其他属性。对我的 User.js 架构的快速修复是:

notifications: [{
        notifType: String,
        story: String,
        seen: Boolean,
        createdTime: Date,
        from: {
            name: String,
            username: String,
            id: mongoose.Schema.ObjectId
    }]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多