node.js - MongoDB - Mongoose,在嵌套查询中添加新文档数据
问题描述
我无法在嵌套查询中推送数据
我无法理解我在代码中遗漏了什么(我是 mongodb 的新手,只是在试验)
我的目标是在帖子中添加“帖子”
const Schema = mongoose.Schema;
const UserDetail = new Schema({
username: String,
password: String,
firstname: String,
lastname: String,
email: String,
posts: {
post:{
title: String,
article: String,
comments: {}
}
}
});
const User = mongoose.model('userInfo', UserDetail, 'userInfo');
module.exports = User;
这是我的更新代码
User.findOneAndUpdate({_id: req.user._id},{ $push: {"posts": { "post" : { "article": req.body.description }} } });
先感谢您
解决方案
$push
用于将指定的值附加到数组。如果要更新的文档中不存在该字段,则添加以该值作为其元素的数组字段,但如果该字段不是数组,则操作将失败。在您的情况下posts
是嵌入式文档,而不是数组。
您可以更新您的架构以创建posts
一个数组:
const Schema = mongoose.Schema;
const UserDetail = new Schema({
username: String,
password: String,
firstname: String,
lastname: String,
email: String,
posts: [
{
title: String,
article: String,
comments: []
}
]
})
然后推
User.findByIdAndUpdate(req.user,
{ "$push": {
"posts": {
"article": req.body.description
}
} }
);
User.findByIdAndUpdate(req.user,
{ "set": { "posts.post.article": req.body.description } }
);
推荐阅读
- r - R readr read_csv 跳过错误与 VROOM_CONNECTION_SIZE
- dialogflow-es - 从 webhook Actions Google 或 Google Assistant 中的 DialogFlow 启动 URL
- c# - 为不同的 EF 对象分解 Linq Where 子句
- html - 每当文本换行使 flex-box 缩小并删除间距时
- mysql - 查询以从不同列中选择日期范围
- javascript - 如何使用firebase查询唯一对?
- javascript - 获取 webpack 输出文件列表并在 PWA 的另一个模块中使用
- python-3.x - Python3.8--Cartopy/Fiona 错误:shapefile 未被识别为支持的文件格式
- json - JSON.parse() 在 ejs 模板的脚本标签中不起作用
- java - 如何在单个测试用例中映射和迭代所有事件