mongoose делает это для вас за одну операцию.
Contact.findByIdAndUpdate(
info._id,
{$push: {"messages": {title: title, msg: msg}}},
{safe: true, upsert: true},
function(err, model) {
console.log(err);
}
);
Пожалуйста, имейте в виду, что с помощью этого метода вы не сможете использовать «pre» функции схемы.
http://mongoosejs.com/docs/middleware.html
По состоянию на последний mogoose findbyidandupdate необходимо иметь «новое: истинное» необязательное Параметр добавлен к нему. В противном случае вы вернете старый документ. Следовательно, обновление для Mongoose Version 4.x.x преобразуется в:
Contact.findByIdAndUpdate(
info._id,
{$push: {"messages": {title: title, msg: msg}}},
{safe: true, upsert: true, new : true},
function(err, model) {
console.log(err);
}
);
Вы можете проверить этот пример.
https://snack.expo.io/@nazrdogan/moody-almond
import * as React from 'react';
import { Text, View, StyleSheet, TouchableHighlight } from 'react-native';
import { Constants } from 'expo';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = { pressStatus: false };
}
_onHideUnderlay() {
this.setState({ pressStatus: false });
}
_onShowUnderlay() {
this.setState({ pressStatus: true });
}
onPress = () => {
}
render() {
return (
<View style={styles.container}>
<TouchableHighlight
onPress={this.onPress}
activeOpacity={1}
underlayColor={"red"}
style={this.state.pressStatus ? styles.buttonPress : styles.button}
onHideUnderlay={() => this._onHideUnderlay()}
onShowUnderlay={() => this._onShowUnderlay()}>
<Text
style={
this.state.pressStatus ? styles.welcomePress : styles.welcome
}>
{'Click Me'}
</Text>
</TouchableHighlight>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent:"center",
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
color: '#000066',
},
welcomePress: {
fontSize: 20,
textAlign: 'center',
margin: 10,
color: '#ffffff',
},
button: {
borderColor: '#000066',
borderWidth: 1,
borderRadius: 10,
},
buttonPress: {
borderColor: 'red',
borderWidth: 1,
borderRadius: 10,
},
});