将对象推入mongoDB,[“object object”]被保存

Pushing object into mongoDB, ["object Object"] is saved

本文关键字:object 保存 对象 mongoDB      更新时间:2023-12-25

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

基本上,我的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);
});

附言:我有deferred.resolve而不是res.end(),因为我在不同的控制器中对一些请求推送通知,所以我没有单独的仅用于通知的路由。(例如:用户有一条新消息,我也发送消息并推送通知)

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

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