簡體   English   中英

Mongoose 無法從 MongoDB 數據庫中獲取數據

[英]Mongoose unable to get data from MongoDB database

我有一個如下所示的模型 (AccountModel.js) 和它的控制器。 我嘗試使用郵遞員更改一個文檔,但盡管數據存在,但我從數據庫事件中獲取了一個空數組。

let mongoose = require('mongoose')
let Schema = mongoose.Schema
var ObjectId = Schema.ObjectId

let mySchema = mongoose.Schema({
account_id:ObjectId,
account_key:String,
message:String,
created_at:Date,
updated_at:Date
})

let MySchema = module.exports = 
mongoose.model('account',mySchema);
module.exports.get = function(callback,limit){
MySchema.find(callback).limit(limit)
}

和 AccountController 如下管理帳戶數據庫。 我已經安慰了查詢和數據庫的輸出。

var mongoose = require('mongoose')
var Account = require('../models/AccountModel')
var ObjectId = mongoose.Types.ObjectId;


exports.setMessage = function(req,res){
query = {account_id:new ObjectId(req.body.acnt_id)}
console.log(query,"...")
Account.find(query,function(err,account_data){
    if(err){
        res.send(err)
    }
    else{
        try{

console.log(account_data,'setWelcomeMessage')
            account_data.message = 
req.body.welcomeMessage
            account_data.updated_at = new Date()
            account_data.save((err,data)=>{
                if(err){
                    console.log(err)
                    res.send(err)
                }
                res.send({"Status":"Success"})
            })
            res.send({"Status":"Success"})  
        }
        catch(e){
            //console.log(e)
            res.send({"Status":"Failed"})
        }
    }
})
}

下面是數據庫

> db.account.find().pretty()
{
"_id" : ObjectId("5c18fea5c5a6a4ebf7999c0b"),
"account_id" : ObjectId("5c18fbefc5a6a4ebf7999c08"),
"account_key" : "UDS1500",
"message" : "testing message",
"created_at" : ISODate("2018-12-18T14:05:25.637Z"),
"updated_at" : ISODate("2018-12-18T14:05:25.637Z")
}
{
"_id" : ObjectId("5c18feffc5a6a4ebf7999c0c"),
"account_id" : ObjectId("5c18fbaac5a6a4ebf7999c07"),
"account_key" : "UDS1299",
"message" : "testing message2",
"created_at" : ISODate("2018-12-18T14:06:55.968Z"),
"updated_at" : ISODate("2018-12-18T14:06:55.968Z")
}

從郵遞員調用后,我得到一個空數組

下面是請求格式

{
  "acnt_id":"5c18fbaac5a6a4ebf7999c07",
  "welcomeMessage":"test message 3!!"
}

控制台如下

{ account_id: 5c18fbaac5a6a4ebf7999c07 } '...'
[] 'setWelcomeMessage'

獲取空數據可能有什么問題? 我在這上面浪費了很多時間。

罪魁禍首是這條線

query = {account_id:new ObjectId(req.body.acnt_id)}

其中語句new ObjectId(req.body.acnt_id)創建一個新的 id(無論您在構造函數中傳遞什么),因此您的查詢失敗,因為數據庫中不會有任何匹配項。 您不一定需要將acnt_id字符串轉換為ObjectId因為 Mongoose 在acnt_id為您執行此操作,但如果需要使用

query = {account_id:mongoose.Types.ObjectId(req.body.acnt_id)}

除此以外

query = {account_id:req.body.acnt_id}

就足夠了。


進行更新的更好方法是使用findOneAndUpdate方法,該方法對模型進行原子更新,主要用於更新數據庫中的單個文檔並將其返回給應用程序,因此您可以重構控制器方法到:

exports.setMessage = (req, res) => {
    const query = { 'account_id': req.body.acnt_id };
    const update = { 
        '$set': {
            'message': req.body.welcomeMessage,
            'updated_at': new Date(),
        }
    };
    const options = { 'new': true };

    Account.findOneAndUpdate(query, update, options, (err, account_data) => {
        if (err){
            res.send(err)
        }
        else {
            console.log(account_data); // logs the updated account document
            res.send({"Status":"Success"})
        }
    });
}

此外,您還可以設置時間戳模式中的其中貓鼬分配createdAtupdatedAt領域的模式和分配的類型為Date ,即

let mySchema = mongoose.Schema({
    account_id: ObjectId,
    account_key: String,
    message: String,
}, { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' } });

.find() 返回一個數組,而不是單個元素。 因此,我建議改用 .findOne() 方法。

謝謝你的回應。 我找到了我的問題的答案。

原因是貓鼬用復數名稱創建了一個模型。 這意味着,在這里我將模型命名為“帳戶”。 但是在數據庫中,它將創建/連接到名為“accounts”的集合。 我不知道貓鼬不創建/連接到名為“帳戶”的集合的原因。 由於沒有以“帳戶”命名的集合,它總是給我一個空的結果。

最后,我將集合名稱更改為“帳戶”。 現在它工作正常。

請評論原因,貓鼬創建/連接到給定模型的復數名稱。

//getting from postman .... give the account id in postman
query = {account_id:req.body.acnt_id};
//there is match in DB--- getting the data
Account.find(query,function(err,account_data){
    if(err){
        res.send(err)
    }
u wana update 
    else{
Accoun.update({account_id:req.body.acnt_id},req.body
};
//on body what you enter in postman that will update and store on DB
IN MY KNOWLEDGE 
// just example 
Model.update

Updates all documents matching conditions using the update clause. All update values are casted to their appropriate types before being sent.

var conditions = { name: 'bourne' }
  , update = { $inc: { visits: 1 }}
  , options = { multi: true };

Model.update(conditions, update, options, callback);

function callback (err, numAffected) {
  // numAffected is the number of updated documents
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM