将对象推入到mongoDB中,被保存
对不起,如果这是一个重复的,我真的不能用这里提供的任何信息解决它。
基本上我在我的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); });
PS:我有deferred.resolve
而不是res.end(),因为我推送一些不同的控制器的请求通知,我没有一个单独的路由只为通知。 (例如:用户有一个新的消息,我发送消息,并推送通知)
我发现为什么mongoDB总是把我的对象转换为String
并给我一个[“对象对象”],原因很简单 – 从不使用保留/通用的单词作为对象。 MongoDB正在将我的notification: {type: String, ...}
为一个字段,该字段包含一个string作为值,而不是作为具有types,可见和其他属性的通知。 我的User.js模式的一个快速修复是:
notifications: [{ notifType: String, story: String, seen: Boolean, createdTime: Date, from: { name: String, username: String, id: mongoose.Schema.ObjectId }]