【发布时间】:2018-07-08 03:53:42
【问题描述】:
我的用户架构包含一个通知属性,它的值是一个对象数组(每个对象都是一个通知)
var UserSchema = new mongoose.Schema({
//a bunch of other user properties.
notifications: [{
notification: String,
directLink: String,
notificationType: Number, //0=vote, 1=comment, 2= answer, 3=post from watched user, 4=watch
onObject: { //not necessary if type (above) is 4
type: String, //post, comment, answer
id: String //id. but not as mongoose object because it is not necessary in this case.
},
date: {type: Date, default: Date.now, index: true},
newNotification: {type: Boolean, default: true}
}]
});
我的问题是当我尝试添加新通知时。当有人发布新内容,或有人回复您的评论等时,调用一个名为 newNotification 的函数,并将要通知的用户作为参数传递给该函数,形式为 post.author(post 是一个猫鼬对象将作者作为其属性之一,其值为用户的 ObjectId,在传递给函数之前填充)。
在新的通知函数中,准备好对象,然后将其推送到 user.notifications 数组:
var newNot = {
notification: notification,
directLink: directLink,
notificationType: action[0],
onObject: on
}
//this code is at the end of the function, newNot now contains the data for the new notification.
//the user is passed in as "notifyUser"
console.log(">>>>>>>>"+notifyUser);
console.log(">>>>>>>>>"+notifyUser.notifications);
notifyUser.notifications.push(newNot);
console.log(">>>>>>>>>>>"+notifyUser.notifications);
console.log(">>>>>>>>>>>>>>>"+notifyUser);
notifyUser.save();
问题是通知没有保存。它工作正常,它作为通知添加给用户。默认设置的它的属性甚至被正确添加。但它不保存 一般方法在另一个用户属性上完美地工作,它只是一个增加的数字,所以这不是问题。但我仍然尝试为用户查询数据库,然后在回调中运行这些东西,但更改仍然没有保存。我花了几个小时试图弄清楚为什么它没有被正确保存,但一无所获。
注意:不,创建通知架构不会更好,在这种特定情况下,没有必要。
【问题讨论】:
-
您可以在插入
notification数组时使用更新查询。这是文档链接:docs.mongodb.com/manual/reference/operator/update/push -
@saikatchakrabortty 所以它会像 User.update({_id: notifyUser._id}, {$push: {notifications: newNot}}); ?
-
是的,
User.update({_id: notifyUser._id}, {$push: {notifications: newNot}}).exec(); -
@saikatchakrabortty 它给了我一个 castError: cast to embedded failed for value(然后是 newNot 的值)。带我到这里stackoverflow.com/questions/43356267/…,但该答案中猫鼬错误的解决方法对我不起作用对我不起作用
-
你可以在这里发布 undate 查询吗?你是如何发送
notifyUser._id的?
标签: mongoose mean-stack