node.js - 在不同时间向 MongoDB 模型添加数据

标签 node.js mongodb express mongoose

我对 mongoose 的 mongdoDB 有很好的理解,但是它的这一方面已经让我困惑了一段时间。我有一个 user.js 模型,其中包含用户名、密码等(所有基本用户内容)。当用户注册帐户时会添加此数据。但每个用户还拥有更多与其关联的数据,这些数据在注册时并未创建或添加。

这是我的模型:

// User Schema
const UserSchema = new Schema({

    // PERSONAL USER INFO
    username: {
        type: String,
        index: true
    },
    email: {
        type: String
    },
    password: {
        type: String
    },

    // INSTAGRAM ACCOUNT INFORMATION
    ig_username: {
        type: String
    },
    ig_password: {
        type: String
    },
    story_price: {
        type: Number
    },
    fullpost_price: {
        type: Number
    },
    halfpost_price: {
        type: Number
    },
    leads: [{
        title: { type: String }
    }]
});

// EXPORTS
const User = module.exports = mongoose.model('user', UserSchema);

除“潜在客户”之外的所有字段都是在注册时创建的。但我想使用另一种形式填写潜在客户字段。我尝试过 .update()、.save()、$set、$push 和各种方法,但我无法让它工作。

我发现的大多数解决方案都使用 var user = new User({...}) 来创建新用户,然后在添加附加数据后使用 .save() 。但这似乎是错误的,因为用户已经创建,而我只是尝试将数据添加到附加字段。

我想我只是掩盖了一些基本的东西,但如果有办法做到这一点,我会很高兴听到它。谢谢!

最佳答案

我会为潜在客户创建一个子架构

// Create a sub-schema for leads
const leadsSubSchema = new Schema({
  title: {
    type: String,
  },
});

// Create a schema for user
const UserSchema = new Schema({
  username: {
    type: String,
    index: true
  },

  // ...

  leads: [leadsSubSchema]
});

// EXPORTS
const User = module.exports = mongoose.model('user', UserSchema);
<小时/>

然后进行更新

User.update({
  _id: user_id,
}, {
  $push: {
    leads: lead_to_add,
  },
});

关于node.js - 在不同时间向 MongoDB 模型添加数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48758497/

相关文章:

node.js - Mongoose - 子文档验证不起作用

javascript - 通过nodejs从mongodb获取数据并express到html页面

javascript - 使用 express 启用 http 压缩

node.js - 如何摆脱 source-map-support TypeError : frame. getFileName 不是 Node 10 中的函数

javascript - 如何改变JSON格式?

mongodb - 改进 MongoDB 中存在的查询字段

javascript - 传递刚刚创建的参数

node.js - 使用 "export * as"语法的node_modules软件包中的 typescript 错误

node.js - 是否可以使用 Cheerio 抓取 React 网站(Instagram)?

node.js - 测试 WebSocket 时如何阻止 Jest 挂起?