Mongodb 如何推入Mongoose子文档数组?
以下是我的模式:Mongodb 如何推入Mongoose子文档数组?,mongodb,mongoose,Mongodb,Mongoose,以下是我的模式: new Schema({ user: [{ email: { type: String }, contactList: [{ frndemail: { type: String }, msgList: [{ from : String, to : String, content : String,
new Schema({
user: [{
email: { type: String },
contactList: [{
frndemail: { type: String },
msgList: [{
from : String,
to : String,
content : String,
time : String,
type: String,
subtype : String,
state: String
}],
unreadmsgList:[{
from : String,
to : String,
content : String,
time : String,
type: String,
subtype : String,
state: String
}]
}]
}]
});
在上面的模式中,我尝试在msgList中推送新消息,但我的查询不起作用,我正在尝试以下操作:
MyModel.update({"user.email":"myemail@gmail.com","user.contactList.frndemail":"frndemail@gmail.com"}, {
$push:{"user.$.contactList.$.msgList":{
"from": "myemail@gmail.com",
"to": "frndemail@gmail.com",
"content": "abc",
"time": "1:00 PM",
"type": "",
"subtype": "",
"state": ""
}}
},
function(err,doc){
if (err) {
console.log("msg creation failed " +err);
} else {
console.log("msg created successfully "+doc);
}
});
如果有人帮我更正此查询,请…是否有任何错误?这是错误:用户消息创建失败CastError:Cast to[string]值“[{”from:”失败myemail@gmail.com“,”至“:”frndemail@gmail.com路径“msgList”处的“,”内容“:”avc“,”时间“:”5:32 PM“,”类型“:”文本“,”子类型“:”文本“,”状态“:”无“}]””一件事是mongo不会允许$positional运算符在一个字段中出现多次。{“user.$.contactList.$.msgList”}我不知道是否需要它,但您的模式需要优化。您应该在不同的模式中保留用户和消息。此外,对于已读和未读消息,也不需要对不同的数组进行修改。