将对象推入mongoDB,[“object object”]被保存
Pushing object into mongoDB, ["object Object"] is saved
很抱歉,如果这是一个重复的问题,我真的无法用这里提供的任何信息来解决它。
基本上,我的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
}]
相关文章:
- 如何将getJson的响应保存在全局变量中
- 按下按钮时保存cookie
- 函数未在Object.keys或Object.getOwnPropertyNames下列出,但可以调用
- 如何使用 Angular JS 将数据保存在数据库中
- 子字符串/正则表达式以获取字符串中保存的 SRC 值
- HTML5在画布中加载较小的图像并保存实际大小的图像
- 是否可以在浏览器中使用纯JavaScript保存音频流
- 如何将多个画布保存为一个图像
- delete在Object上效率低下,但在DOM Element's的数据属性,与null out相比
- PHP:显示sqlite数据库中的html格式数据,使用tinymce保存
- 如何将乳胶配方奶粉图像保存到Asp.net中的文件夹中
- 保存数组javascript
- 有没有一种方法可以列出Ember.Object的所有绑定
- 保存串行端口列表与流星
- 如何取消object.prototypes javascript的一个函数
- 将JavaScript变量保存到Rails模型
- 将对象推入mongoDB,[“object object”]被保存
- 分析:[Error]:错误:Can't序列化未保存的Parse.Object
- MongooseJS:`TypeError:Object#<对象>没有方法'保存'`:无法保
- Id在mongodb数据库中保存为[object]