繁体   English   中英

如何在模式中未存在的MongoDB中的现有文档中定义新字段? (Node.js)

[英]How to define a new field in a pre-existing document in MongoDB that isn't in the schema? (Node.js)

我正在使用MongoDB做一个不和谐的机器人,我想将一些特定于用户的字段添加到不在模式中的MongoDB中已经存在的文档中。 我打算添加很多数据,我希望根据用户为提高效率而自动添加数据。

我试图使用findOneAndUpdate设置新字段及其值。 我将设置“ strict”设置为false,将“ upsert”设置为true。 我后来保存了。 我确实看到它是在Compass社区应用程序中添加的,但是当我稍后尝试调用该字段时,它是未定义的,我假设是因为它不在架构中。 我想知道是否可以解决此问题,或者是否出错。

Users.findOneAndUpdate({
  userID: message.author.id
}, {
  $set: {
    "xp": xpToBeAdded,
    "level": 0
   }
}, {
  strict: false,
  upsert: true
}, async (err, userAdd) => {
  await userAdd.save().catch(err => console.log(err))
})

原始用户架构:

const mongoose = require("mongoose");

const userSchema = mongoose.Schema({
    userID: String,
    serverID: Array,
    userTag: String,
    username: String,
    dbCreatedAt: Number,
    dbCreatedAtDate: String
}, {strict: false})

module.exports = mongoose.model("User", userSchema)

如果您在罗盘中看到了正确的值,但没有返回,则可能是因为您的模型不知道这些属性。 尝试将模型更新为此:

const mongoose = require("mongoose");

const userSchema = mongoose.Schema({
    userID: String,
    xp: Number,
    level: Number,
    serverID: Array,
    userTag: String,
    username: String,
    dbCreatedAt: Number,
    dbCreatedAtDate: String
}, {strict: false})

module.exports = mongoose.model("User", userSchema)

发生的情况的示例(注意,即使您将性作为值传递,也不会记录sex ):

 class User { constructor(user) { this.name = user.name; this.age = user.age; } } const user1 = new User({name: 'Frank', age: 22, sex: 'M'}); console.log(user1); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM