无法在MongoDB(猫鼬)文档中附加数组

Hope2Code:

我试图在mongo数据库中使用在前端(网站ui)中创建的String附加一个空数组,相关代码段如下:

猫鼬图式

    email: String,
    displayName: String,
    googleId: String,
    toIgnore: [{toIgnoreURL: String}]
})

使用通行证和Passport-google-oauth20创建文档

User.findOne({email: email.emails[0].value}).then((currentUser)=>{
            if(currentUser){
                // user does already exist
                console.log('welcome back!', currentUser)
                done(null, currentUser)
            }
            else{ // user doesn't exist yet
            new User({
                email: email.emails[0].value,
                displayName: email.displayName,
                googleId: email.id,
                toIgnore: []
            }).save().then((newUser)=>{
                console.log('new user created: ' + newUser)
                done(null, newUser)
            });
            }
        })

最后,尝试附加“用户”集合(当前登录用户的)的toIgnore数组属性

User.update(
        {email: emailThisSession},
        {$push: {toIgnore: {toIgnoreURL: url}}})

在mongodb中,我看到成功创建了以下文档

_id
:ObjectId(
IdOfDocumentInMongoDB)
toIgnore
:
Array
email
:
"myactualtestemail"
googleId
:
"longgoogleidonlynumbers"
__v
:
0

(也如图所示)mongodb ui中的文档

我似乎不知道如何实际填充'toIgnore'数组。例如,当控制台记录以下内容时

var ignoreList = User.findOne({email:emailThisSession}).toIgnore;
console.log(ignoreList)

输出为undefined注意控制台记录url变量确实会打印我要附加到数组的值!我尝试了在Schema构建器和文档创建中可以想到的任何格式组合,但是找不到合适的方法来完成它!任何帮助,将不胜感激!

使用诺言进行更新也不起作用

User.findOne({email:emailThisSession}).then((currentUser)=>{ //adding .exec() after findOne({query}) does not help as in User.findOne({email:emailThisSession}).exec().then(...)
            console.log(currentUser.toIgnore, url) //output is empty array and proper value for url variable, empty array meaning []
            currentUser.toIgnore.push(url)
        });

如下调整架构:

const userSchema = new Schema({
    email: String,
    displayName: String,
    googleId: String,
    toIgnore: []
})

我只需要将update命令更改为

User.updateOne(
            {email: emailThisSession},
            {$push: {toIgnore: {toIgnoreURL: url}}}).then((user)=>{
                console.log(user)
            })

谢谢@yaya!

yaya:

无法使用猫鼬在文档中添加数组元素

  1. 将您的架构定义为:
const UserSchema = new mongoose.Schema({
  ...
  toIgnore: [{toIgnoreURL: String}]
})
  1. 那么您可以创建一个像这样的对象:
new User({
  ...,
  toIgnore: [] // <-- optional, you can remove it
})
  1. 要检查值:
User.findOne({...}).then(user => {
  console.log(user.toIgnore)
});
  1. 您的更新声明应为:
User.update(
  {email: emailThisSession},
  {$push: {toIgnore: {toIgnoreURL: url}}}
).then(user => {
  console.log(user)
})

因此,在您的情况下,这是未定义的:

User.findOne({email:emailThisSession}).toIgnore

由于findOne是异步的。要获取结果,您可以将其传递给回调函数,也可以使用promises(User.findOne({...}).then(user => console.log(user.toIgnore))

更新:

如下调整架构: new Schema({..., toIgnore: []})

这是您更新的问题。您应该将其更改为:toIgnore: [{toIgnoreURL: String}]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章