简体   繁体   中英

How to query in mongoose/nodejs using Document Object

In my NodeJS code, I'm using mongoose to handle the DB calls.
In my code I've below lines of code that will first update the "NewsReport" record, and based on the response document, I've to update "News" record based to newsId of the document. Here's my code:

NewsReport.findOneAndUpdate({ _id: req.params.reportId }, { $set: { 'status': statusReceived } })
    .then(result => {
        News.findOneAndUpdate({ _id: result.newsId }, { $set: { 'blocked': true } })
            .then(updatedNews => {
                res.status(200).json({
                    message: 'Successfully updated report'
                });
            });
    } else {
            res.status(200).json({
                message: 'Successfully updated report'
            });
        }
    })

My NewsReport schema is as below (the document that will be returned after first update call:

var newsReportSchema = mongoose.Schema({
    newsId: { type: mongoose.Schema.Types.ObjectId, ref: 'News', required: true },
    creator: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
    type: { type: String, enum: Constants.reportTypes, required: true },
    status: { type: String, enum: Constants.reportStatus, default: 'None' }
};

module.exports = mongoose.model('NewsReport', newsReportSchema);

Its failing because "result.newsId" returns an Object. How can I use "findAndUpdate" based on the document object?

NewsReport.findOneAndUpdate({ _id: req.params.reportId }, { $set: { 'status': statusReceived } })
.then(result => {
    result.depopulate('newsId');
    News.findOneAndUpdate({ _id: result.newsId }, { $set: { 'blocked': true } })
        .then(updatedNews => {
            res.status(200).json({
                message: 'Successfully updated report'
            });
        });
} else {
        res.status(200).json({
            message: 'Successfully updated report'
        });
    }
}) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM