简体   繁体   中英

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

I am making a discord bot using MongoDB and I want to add some user-specific fields to an already existing document in MongoDB that aren't in the schema. There is a lot of data I am planning to add and I wanted it to be added automatically depending on what the user does for efficiency.

I tried to use findOneAndUpdate to set the new field and its value. I had the settings "strict" set to false and "upsert" set to true. I saved it afterwards. I did see that it was added in the Compass Community App, but when I tried to call the field later, it was undefined and I'm assuming because it isn't in the schema. I wanted to know if there was a way around this or if I made any errors.

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

Original users schema:

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)

If you are seeing the right values in compass, but it's not being returned, it's probably because your model doesn't know about those properties. Try updating your model to this:

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)

Example of what is happening (notice how sex doesn't get logged, even though you're passing it in as a value):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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