Node.js保存到mongoDB

时间:2019-05-06 11:41:28

标签: node.js mongodb

我想将数据保存到数据库,但是在这种情况下我不知道该怎么做。

userModel.js

const userSchema = new mongoose.Schema({
  email: {
    type: String,
    unique: true
  },
  password: String,
  passwordResetToken: String,
  passwordResetExpires: Date,

  profile: {
    firstname: String,
    lastname: String,
    gender: String,
    status: String,
    location: String,
    website: String,
    picture: String
  }
});

Signup.js

 const user = new User({
    firstname: req.body.firstname,
    lastname: req.body.lastname,
    location: req.body.location,
    status: 0,
    email: req.body.email,
    password: req.body.password
  });

问题是配置文件中的那些内容无法保存,我不知道如何编辑signup.js以使其正常工作。像profile.firstname: req.body.firstname之类的东西不起作用。

2 个答案:

答案 0 :(得分:2)

const user = new User({
    profile: {
        firstname: req.body.firstname,
        lastname: req.body.lastname,
        location: req.body.location,
        status: 0,
    },
    email: req.body.email,
    password: req.body.password
});

从架构(userModel.js),我们需要使用profile结构进行更新

答案 1 :(得分:1)

您需要像这样保存在signUp.js

const user = new User({
    profile :{
        firstname: req.body.firstname,
        lastname: req.body.lastname,
        location: req.body.location,
        status: 0
    },
    email: req.body.email,
    password: req.body.password
  });

由于firstnamelastnamelocationstatusprofile对象的一部分。