gpt4 book ai didi

javascript - Mongoose 无法从 MongoDB 数据库获取数据

转载 作者:行者123 更新时间:2023-11-30 19:55:14 25 4
gpt4 key购买 nike

我有一个如下所示的模型 (AccountModel.js) 和它的 Controller 。我尝试使用 postman 更改一个文档,但尽管数据存在,但我从数据库事件中得到一个空数组。

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")
}

从 POSTMAN 调用后我得到一个空数组

请求格式如下

{
"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(不管你在构造函数中传递了什么)因此你的查询失败,因为在D b。您不一定需要将 acnt_id 字符串转换为 ObjectId,因为 Mongoose 会在后台为您执行此操作,但如果需要,请使用

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

否则

query = {account_id:req.body.acnt_id}

就足够了。


进行更新的更好方法是使用 findOneAndUpdate对模型进行原子更新的方法,主要用于更新数据库中的单个文档并将其返回给应用程序时,因此您可以将 Controller 方法重构为:

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"})
}
});
}

此外,您还可以设置 timestamps在您的模式中,mongoose 将 createdAtupdatedAt 字段分配给您的模式,并且分配的类型是 Date

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

关于javascript - Mongoose 无法从 MongoDB 数据库获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54070204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com