首页 > 解决方案 > 无法使用 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 ) );
} )

标签: javascriptnode.jsmongodb

解决方案


推荐阅读