javascript - 无法使用 node.js 保存到 mongodb
问题描述
我正在尝试使用 node.js 在 mongodb 中保存 id 数组。我收到书签为空的错误 //bookmarks.sites.push(element._id); element._id 来自 request.body。
有超过 1 个站点 ID 将从该表单中传递,[{"_id":"5e88d1e5a9162a308dc55999"},{"_id":"5e88d1e5a9162a308dc55998"} ]
在确认用户有效后,我正在使用 forEach 遍历上述元素。这将在 sites:[] 数组中添加站点 ID。
我正在使用 foreach 循环遍历并检查站点 ID 是否不存在,然后推送 element._id。但是当我发送帖子请求时,
console.log('bookmarks 1 = ', bookmarks);
this statement prints bookamrks 1 = null
我想知道为什么它打印空
谢谢
const bookmarkSchema = new Schema( { user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}, sites: [{ type: mongoose.Schema.Types.ObjectId,
ref: 'Bookmark'}]
} );
post( cors.corsWithOptions, authenticate.verifyUser, ( req, res, next ) => {
Bookmark.findOne( { user: req.user._id } ) //matching user._id from request returned fav document
.then( bookmarks => {
//console.log('req,user._id = ', req.user._id);
//if (bookmarks) {
req.body.forEach(
element => {
console.log( 'bookmarks = ', bookmars );
console.log( 'element id outxidf T = ', element._id );
//console.log('req.body = ', req.body);
if (
//! tests for missing favorites
!bookmarks.sites.includes( element._id ) //from the request
)
console.log( 'element id = ', element._id );
//bookmarks.sites.push(element._id); */
}
//test for campsiteIDs in teh request body and check for existence in the Bookmark document
//
);
console.log( 'bookmarkss = ', bookmarks );
//bookmarks.save();
//}//if
//Bookmark.create(req.body);
} ) //loop through fav documents
//next thing in my loop I will test for campsiteObjectId from the body response.
//.create(req.body)
.then( s => {
console.log( 'Favorites Created ', favorites );
res.statusCode = 200;
res.setHeader( 'Content-Type', 'application/json' );
res.json( bookmarks );
} )
.catch( err => next( err ) );
} )
解决方案
推荐阅读
- python - 为什么我的 ema 15 和 ema 200 看起来一样?
- office365 - Microsoft Teams 对话存储
- node.js - 处理 aws-sdk 存储桶创建请求 nodejs express
- java - csv文件和操作
- c++ - 在 C++ 中执行嵌套 STRUCT 时出错
- java - Postgresql 进化数据库“默认”处于不一致状态。错误:“用户”位置或附近的语法错误:12 [错误:0,SQLSTATE:42601]
- sql - 按日期顺序以 mm-yyyy 格式排序字符串
- javascript - FormData 的字典在 Flask 中创建不好
- azure - 找不到测试文件时如何使 AzureDevops 管道失败
- amazon-redshift - Redshift - 没有架构绑定