gpt4 book ai didi

javascript - 从提示符中获取数组并插入 MongoDB 数据库

转载 作者:行者123 更新时间:2023-12-03 04:52:40 25 4
gpt4 key购买 nike

我正在开发一个社交网络类型的网站。我想要一种可以提示用户,在数组中获取他们的响应,然后一次插入数组的方法。虽然我可以提示我在将数组插入 mongodb 数据库时遇到问题。这是我的代码:

'click #creator': function(event){

var channelName = prompt('Enter The Channel Name');
var howmany = +prompt('How many people do you want? (max 10)');
var users = [];
var arr = []; // define our array

if(howmany > 1 && howmany<10){
for (var i = 0; i < howmany; i++) { // loop 10 times
arr.push(prompt('Enter a user' + (i+1))); // push the value into the array
}

users = arr.join('"," ');
Meteor.call('addChannel', channelName, users);
}
}

将其插入:

 Channels = new Mongo.Collection('channels');
Meteor.methods({
addChannel: function(channelName, users){
if(!Meteor.userId()) {
throw new Meteor.Error('not-authorized', 'you are not signed in');
}

var username = Meteor.user().username;

Channels.insert({
name: channelName,
created: new Date(),
members: $push: {users}
createdBy: username
});
},
});

最佳答案

由于您正在插入并且 users 已经是一个数组,因此您不需要 $push。另外,您不需要推送 {} 对象。

Channels.insert({
name: channelName,
created: new Date(),
members: users,
createdBy: username
});

同时在客户端,跳过 arr.join() - 这是创建一个字符串,但您只想直接传递您创建的数组。

Meteor.call('addChannel', channelName, arr);

关于javascript - 从提示符中获取数组并插入 MongoDB 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42589980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com