将对象和额外属性通过Axios发送到Express服务器,并使用Mongoose保存。

huangapple go评论73阅读模式
英文:

Send object and additional attributes to express server via Axios and save with Mongoose

问题

你想要将用户对象和一个简单的字符串通过axios post发送到后端,然后使用mongoose将这些数据存储在MongoDB中。如果我只发送用户对象而不发送浏览器字符串,也就是说只在后端处理用户对象,一切都正常运行。该对象具有所有属性,除了浏览器属性。我稍后添加了这个属性。那么我如何才能一对一地保存用户对象,并保存其他属性,比如这里的浏览器属性?实际上只保存了浏览器字符串。

在保存新用户的mongoose函数中:

export const newUser = async (req, res, next) => {
  try {
    const user = new User({ ...req.body.userD, browser: req.body.browser });

    const savedUser = await user.save();

    const myPromise = new Promise((resolve, reject) => {
      resolve(savedUser);
    });

    myPromise.then(() => {
      res.status(200).json("用户已保存");
    });
  } catch (error) {
    next(err);
  }
};

axios post:

let config = {
  method: 'post',
  maxBodyLength: Infinity,
  url: 'http://localhost:3999/server/user/new',
  headers: { 
    'Content-Type': 'application/json'
  },
  userD: data,
  browser: browser
};

await axios.request(config)
  .then((result) => {
    res.end(result.data)
  })

用户模型:

import mongoose from "mongoose";

const UserSchema = new mongoose.Schema(
  {
    // 属性列表...
    browser: {
      type: String,
    },
  },
  { timestamps: true }
);

export default mongoose.model("User", UserSchema);

如果你发送的数据如下:

{
  "data":{
    "ip":"2003:c4:f720.xxx",
    "network":"2003:xxx",
    "version":"IPv6",
    "city":"xxxx",
    "region":"xxxx",
    "region_code":"BW",
    "country":"DE",
    "country_name":"Germany",
    "country_code":"DE",
    "country_code_iso3":"DEU",
    "country_capital":"Berlin",
    "country_tld":".de",
    "continent_code":"EU",
    "in_eu":true,
    "postal":"xxxx",
    "latitude":xxxx,
    "longitude":x.xx,
    "timezone":"Europe/Berlin",
    "utc_offset":"+0200",
    "country_calling_code":"+49",
    "currency":"EUR",
    "currency_name":"Euro",
    "languages":"de",
    "country_area":357021,
    "country_population":82927922,
    "asn":"AS3320",
    "org":"Deutsche Telekom AG"
  },
  "browser":"Browser"
}

在MongoDB中将会保存包含所有属性的用户对象,包括浏览器属性。

英文:

I'm posting a user object and a simple string to the backend via axios post and then want to store this data in MongoDB using mongoose. If I send the whole thing without the browser string, i.e. only the user object and process it in the backend, everything works. The object has all attributes except for the browser attribute. I added this later. So how can I save the user object 1:1 and also save other attributes, such as the browser attribute here? All that is actually saved is just the browser string

Function for save new User with mongoose:

//CREATE NEW USER
export const newUser = async (req, res, next) => {
try {
 const user = new User({ ...req.body.userD, browser: req.body.browser });

 const savedUser = await user.save();

 const myPromise = new Promise((resolve, reject) => {
   resolve(savedUser);
 });

 myPromise.then(() => {
  res.status(200).json("User saved");
 });

 } catch (error) {
  next(err);
 }
};

axios post :

let config = {
    method: 'post',
    maxBodyLength: Infinity,
    url: 'http://localhost:3999/server/user/new',
    headers: { 
      'Content-Type': 'application/json'
    },
    userD: data,
    browser:browser
};

await axios.request(config)
  .then((result) => {
    res.end(result.data)
  })

User Model:

import mongoose from "mongoose";

const UserSchema = new mongoose.Schema(
{
asn: {
  type: String,
},
city: {
  type: String,
},
continent_code: {
  type: String,
},
country: {
  type: String,
},
country_area: {
  type: Number,
},
country_calling_code: {
  type: String,
},
country_capital: {
  type: String,
},
country_code: {
  type: String,
},
country_code_iso3: {
  type: String,
},
country_name: {
  type: String,
},
country_population: {
  type: Number,
},
country_tld: {
  type: String,
},
currency: {
  type: String,
},
currency_name: {
  type: String,
},

in_eu: {
  type: Boolean,
},
ip: {
  type: String,
},
languages: {
  type: String,
},

latitude: {
  type: Number,
},
longitude: {
  type: Number,
},
network: {
  type: String,
},

org: {
  type: String,
},
postal: {
  type: Number,
},
region: {
  type: String,
},

region_code: {
  type: String,
},
timezone: {
  type: String,
},
utc_offset: {
  type: String,
},
version: {
  type: String,
},
browser: {
  type: String,
},
},
{ timestamps: true }
);

export default mongoose.model("User", UserSchema);

UPDATE

This is the data which is send to the express server:

> {
"data":{
"ip":"2003:c4:f720.xxx",
"network":"2003:xxx",
"version":"IPv6",
"city":"xxxx",
"region":"xxxx",
"region_code":"BW",
"country":"DE",
"country_name":"Germany",
"country_code":"DE",
"country_code_iso3":"DEU",
"country_capital":"Berlin",
"country_tld":".de",
"continent_code":"EU",
"in_eu":true,
"postal":"xxxx",
"latitude":xxxx,
"longitude":x.xx,
"timezone":"Europe/Berlin",
"utc_offset":"+0200",
"country_calling_code":"+49",
"currency":"EUR",
"currency_name":"Euro",
"languages":"de",
"country_area":357021,
"country_population":82927922,
"asn":"AS3320",
"org":"Deutsche Telekom AG"
},
"browser":"Browser"
}

and this is what is saved in mongodb
将对象和额外属性通过Axios发送到Express服务器,并使用Mongoose保存。

答案1

得分: 0

从你的编辑部分我看到你需要访问“data”字段然后展开…

const user = new User({…req.body.userD.data, browser:req.body.browser})
英文:

From your edit part I see that you need to access the ‘data’ field and than spread…

const user = new User({…req.body.userD.data, browser:req.body.browser})

huangapple
  • 本文由 发表于 2023年5月6日 18:54:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76188479.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定